文章目录

  • 1.什么是OutputStream?(输出流)
  • 2.使用FileOutputStream写出文件
  • 2.1 void write(int b) 向目的地写入一个字节
  • 2.2 void write(byte b[]) 向目的地写入多个字节
  • 2.3 void write(byte b[], int off, int len) 向目的地写入指定多个字节
  • 2.4 void flush() 如果使用的是缓冲流,需要调用这个方法一次写出


1.什么是OutputStream?(输出流)

在JavaAPI中,我们将可以向目的地写入一个字节序列的对象称为输出流。字节序列的来源地可以是文件,也可以是网络,还可以是内存块等等。
输出流根据每次写出的字节数量的不同分为字节输出流和字符输出流。 字节输出流每次都是写出一个字节的,而字符输出流每次写出都是根据基于两字节的字符为单位写出的。

2.使用FileOutputStream写出文件

在outputStream中的关键常用的方法是:write方法。

2.1 void write(int b) 向目的地写入一个字节

这个方法向目的地写入一个字节

/**
 * 每次写入单个字节
 * @throws IOException
 */
public static void writeStudy() throws IOException {
    OutputStream outputStream = new FileOutputStream("四郎.txt");
    String str = "我是四郎";
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
    for (byte b:bytes){
        outputStream.write(b);
    }
}

JavaIO流输出文件 java outputstream输出文件_输出流

2.2 void write(byte b[]) 向目的地写入多个字节

这个方法一次向目的地写入多个字节。

/**
 * 一次写入多个字节
 * @throws IOException
 */
public static void writeBytesStudy() throws IOException {
    OutputStream outputStream = new FileOutputStream("四郎.txt");
    String str = "我是四郎";
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
    outputStream.write(bytes);
}

JavaIO流输出文件 java outputstream输出文件_输出流_02

2.3 void write(byte b[], int off, int len) 向目的地写入指定多个字节

一次性写入字节数组b中指定范围的数据到目的地

/**
 * 从指定字节数组中选一部分进行写入
 * @throws IOException
 */
public static void writeBytesLenStudy() throws IOException {
    OutputStream outputStream = new FileOutputStream("四郎.txt");
    String str = "我是四郎";
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
    outputStream.write(bytes,2,2);
}

JavaIO流输出文件 java outputstream输出文件_数据_03

2.4 void flush() 如果使用的是缓冲流,需要调用这个方法一次写出

对于缓冲输出流,它的write方法并不会立即向磁盘中写入数据,而需要缓存满了或者调用flush方法立即写入

/**
 * 对于缓冲输出流,它的write方法并不会立即向磁盘中写入数据,
 * 而需要缓存满了或者调用flush方法立即写入
 * @throws IOException
 */
public static void flushStudy() throws IOException {
    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("四郎.txt"));
    String str = "我是四郎";
    byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
    outputStream.write(bytes);
    outputStream.flush();
}

JavaIO流输出文件 java outputstream输出文件_输出流_04