【java高级】java.io.OutputStream

一.概述

和java.io.InputStream相反,java.io.OutStream是java标准库提供的最基本的输出流,它是一个抽象类,是所有输出流的超类。其中有一个write()方法,会写入输出流的下一个字节,写入int值(0~255)。

二.FileOutStream

与FileInputStream类似,这里只是简单说明一下区别。

package com.sdnu.project1;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * @author Beyong
 * @Description FileOutStream
 * @date 2021/05/24 20:46
 */

public class Demo3 {
    public static void main(String[] args) {
        FileOutputStream file = null;
        try{
            byte[] buffer = {97, 98, 99, 100, 101};
            file = new FileOutputStream("myFile.txt");
            file.write(buffer);
            file.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

  • flush()用于刷新缓冲区数据,也就是将缓冲区的残留数据全部写如目的地,防止数据丢失。
  • 我们上面的例子会覆盖原来文件的内容,如果我们想要追加,可以使用第二个构造函数,如下:
    file = new FileOutputStream("myFile.txt",true);

三.实例

package com.sdnu.project1;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * @author Beyong
 * @Description FileOutStream
 * @date 2021/05/24 20:46
 */

public class Demo3 {
    public static void main(String[] args) {
        FileOutputStream file = null;
        try{
            String str = "I like China";
            byte[] buffer = str.getBytes();
            file = new FileOutputStream("myFile.txt",true);
            file.write(buffer);
            file.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我们通过getBytes()能将任意一个字符串变成字节数据,然后就可以写入了。

作者:Beyong    
出处:Beyong博客
github地址:https://github.com/beyong2019


本博客中未标明转载的文章归作者Beyong有,欢迎转载,但未经作者同意必须保留此段声明,且在文章明显位置给出原文连接,否则保留追究法律责任的权利。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值