三、java IO--使用字节流写入文件

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
    二、写出文件
    1、建立联系   File对象  目的地
    2、选择流     文件输出流  OutputStream FileOutputStream
    3、操作  :  write() +flush
    4、释放资源 :关闭
 */
public class WriteFile {
    public static void main(String[] args) {
        String str = "F:/write.txt";
        mywrite(str);
    }
    public static void mywrite(String str){
        File file = new File(str);    //1、建立连接
        OutputStream os = null;
        try {
            //2、选择输出流,以追加形式(在原有内容上追加) 写出文件 必须为true 否则为覆盖
            os = new FileOutputStream(file,true);    
//            //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输出效率,建议
//            os = new BufferedOutputStream(new FileOutputStream(file,true));
            String string = "Programmer say : Hello World!";
            byte[] data = string.getBytes();    //将字符串转换为字节数组,方便下面写入

            os.write(data, 0, data.length);    //3、写入文件
            os.flush();    //将存储在管道中的数据强制刷新出去
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件没有找到!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("写入文件失败!");
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("关闭输出流失败!");
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/jiaoqiang/p/8378412.html