20.2 Java写文件之OutputStream学习

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);
    }
}

在这里插入图片描述

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);
}

在这里插入图片描述

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);
}

在这里插入图片描述

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();
}

在这里插入图片描述

代码地址:Java基础学习/src/main/java/Progress/exa20 · 严家豆/Study - 码云 - 开源中国 (gitee.com)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小牧之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值