IO流--向文档添加内容

目的:向文本文档写出内容(如果没有该文档,则会自动创建)
思路:

          使用相对路径找到文档地址;
           写出方法!
           刷新页面,保证代码写进硬盘内!
           使用finally写出关流

代码:

     

 1  public static void main(String[]args){
 2        FileOutputStream fos = null;
 3        try {
 4           //true,在新建的文档内可以书写内容,否则不行
 5          fos = new FileOutputStream("aaa.txt",true);
 6          String msg="Hello word";
 7          String msgl="你好1";
 8          //换行,需要异常最大化
 9          // 
换行 ,msg执行代码
10          fos.write("
".getBytes());
11          fos.write(msg.getBytes());
12          
13          fos.write("
".getBytes());
14          fos.write(msgl.getBytes());
15          //刷新,保证内存中内容全部写入到硬盘的文件中
16          fos.flush();
17     } catch (FileNotFoundException e) {
18         // TODO Auto-generated catch block
19         e.printStackTrace();
20     } catch (IOException e) {
21         // TODO Auto-generated catch block
22         e.printStackTrace();
23         //以上报错,finally照样执行
24     }finally{
25         
26         try {
27             //减少内存浪费
28             fos.close();
29         } catch (IOException e) {
30             // TODO Auto-generated catch block
31             e.printStackTrace();
32         }
33     }
34    }
 public static void main(String[]args){
       FileOutputStream fos = null;
       try {
          //true,在新建的文档内可以书写内容,否则不行
         fos = new FileOutputStream("aaa.txt",true);
         String msg="Hello word";
         String msgl="你好1";
         //换行,需要异常最大化
         // 
换行 ,msg执行代码
         fos.write("
".getBytes());
         fos.write(msg.getBytes());
         
         fos.write("
".getBytes());
         fos.write(msgl.getBytes());
         //刷新,保证内存中内容全部写入到硬盘的文件中
         fos.flush();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //以上报错,finally照样执行
    }finally{
        
        try {
            //减少内存浪费
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   }
点击
原文地址:https://www.cnblogs.com/wsx123/p/13681172.html