JAVA系列 01:OutputStream

Published: 10 Jun 2018 Category: java

#### —

通过字节流的方式写入文件(FileOutputStream)
 public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        FileOutputStream fos=new FileOutputStream("d:\\abc.txt");
        String str="这是一个测试文档";
        fos.write(str.getBytes());//将字符串转成字节数组
        fos.close();
    }

通过字符流的方式写入文件(FileWrite)
 public static void main(String[] args) throws IOException {
        FileWriter fw=new FileWriter("d:\\def.txt");
        String str="这是第二个测试文档";
        fw.write(str);
        fw.close(); //如果不使用close,则创建的文件没有内容,因此在写入后要及时关闭
    }

JAVA 的API规范:
  • FileOutputStream用于写入诸如图像数据之类的原始字节流。要编写字符流,请考虑使用FileWriter。
  • 如果你熟悉设计模式,FileWriter实际上是Decorator模式的典型用法。我使用简单的教程来演示Decorator模式,因为它对许多设计非常重要,非常有用。 FileOutputStream的一个应用是将文件转换为字节数组。

    1. https://www.jianshu.com/p/bb3ac2c8bae0
    1. https://www.jianshu.com/p/6d9b797e64cf
    1. 见参考链接3

参考链接: