java字节流输出的使用步骤

字节流输出的使用步骤:

  1. 创建一个FileOutPutStream对象,构造方法中传递写入数据的目的地。

  2. 调用FileOutPutStream对象中的方法write,把数据写入到文件中。

  3. 释放资源

     //创建一个File对象
     File file = new File("./a.txt");
     //创建一个文件
     file.createNewFile();
     //创建字节输出流
     FileOutputStream stream = new FileOutputStream(file);
     //写入97->a
     stream.write(97);
     //释放资源
     stream.close();
    

多个字节的写入方法:

  1. public void write(byte[] b); 将b.length字节从指定的字节数组写入此流中
  2. public void write(byte[] b, int off, int len); 从指定的字节数组写入len字节,从偏移量off开始输出到此流中

字符串的写入方法:

  1. String类中有一个getBytes()方法返回指定字符串的字节数组,然后在使用FileOutPutStream的write写入文件中

     public static void main(String[] args)throws Exception {
            byte[] b = "你好".getBytes();
            FileOutputStream fs = new FileOutputStream("./b.txt");
            fs.write(b);
            fs.close();
        }
    

追加写:使用两个参数的构造方法

  1. FileOutPutStream(String name, boolean append)
  2. FileOutPutStream(File file, boolean append)

参:

  • String name,File file:写入数据的目的地

  • boolean append:追加写的开关

    • true:创建的对象不会覆盖原文件

    • false:创建一个新的文件,覆盖原文件

  • 换行写

    • \r\n 注意:也必须转化为字节
posted @ 2022-10-06 13:07  彼时听风  阅读(382)  评论(0)    收藏  举报