FileOutputStream输出字符流

FileOutputStream案例1:

package com.javaSe.FileOutputStream;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class FileOutputStreamTest01 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            // myFile文件不存在的时候会自动新建。
            // 这种方式谨慎使用,这种方式会将原来的文件清空,然后重新写入。
            // fos = new FileOutputStream("myFile");
            
            // 以追加的方式在文件末尾写入,不会清空源文件内容。 在后面加一个true
            fos = new FileOutputStream("myFile",true);
            
            // 开始写
            byte[] bytes = {97,98,99,100};
            // 将 byte数组全部写出。
            fos.write(bytes);
            
            // 将byte数组的一部分写出!
            fos.write(bytes,0,2); // 再写出ab  结果就是abcdab
            
            // 创建字符串
            String s = "我是一个中国人,我骄傲!!!";
            // 将字符串转换成byte数组
            byte[] bs = s.getBytes();
            
            // 写入到文件当中。
            fos.write(bs);
            
            // 写完之后,最后一定要刷新。
            fos.flush();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/xlwu/p/13466087.html