码迷,mamicode.com
首页 > 其他好文 > 详细

FileOutputStream

时间:2018-05-09 17:27:00      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:flush   tac   tput   写入文件   通过   finally   span   参数   ring   

    /* 使用FileOutputStream写入文件,FileOutputStream的write() 方法只接受byte[] 类型 
       的参数,所以需要将string通过getBytes()方法转换为字节数组。 
    1、首先判断文件是否存在,不存在就新建一个 
    2、写入文件是以覆盖方式 
    3、文件不存在会自动创建,存在则会被重写 
     */  
      
    import java.io.*;  
      
    public class Exercise {  
        
      public static void main(String args[]) {  
        FileOutputStream fos = null;  
        File file;  
        String mycontent = "This is my Data which needs to be written into the file.";  
        try {  
          file = new File("/home/zjz/Desktop/myFile.txt");  
          fos = new FileOutputStream(file);  
          byte[] bytesArray = mycontent.getBytes();  
          fos.write(bytesArray);  
          fos.flush();  
          System.out.println("File Written Successfully");  
        } catch (FileNotFoundException e) {  
          e.printStackTrace();  
        } catch (IOException e) {  
          e.printStackTrace();  
        } finally {  
          try {  
            if (fos != null) {  
              fos.close();  
            }  
          } catch (IOException ioe) {  
            System.out.println("Error in closing the Stream");  
          }  
        }  
      }  
      
    }  

 

FileOutputStream

标签:flush   tac   tput   写入文件   通过   finally   span   参数   ring   

原文地址:https://www.cnblogs.com/xwb583312435/p/9015381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!