Java--文件字节输出流

字节输出流

InputStream 是 Java 所有字节输入流类的父类,OutputStream 是 Java 所有字节输出流类的父类,它们都是一个抽象类,因此继承它们的子类要重新定义父类中的抽象方法。

子类

OutputStream 类及其子类的对象表示一个字节输出流。OutputStream 类的常用子类如下:

  • ByteArrayOutputStream 类:向内存缓冲区的字节数组中写数据。
  • FileOutputStream 类:向文件中写数据。
  • PipedOutputStream 类:连接到一个 PipedlntputStream(管道输入流)。
  • ObjectOutputStream 类:将对象序列化。

构造方法

输出流的构造方法 如果文件不存在 则会自动创建
如果路径不存在则报错
FileOutputStream(File file)
FileOutputStream(String name)

实例:write的使用
每使用一次write方法,都会将文本里面原本的数据覆盖掉

 public static void main(String[] args) {
        //文件字节输出流
        try( FileOutputStream output = new FileOutputStream("test.txt")){
           output.write("hello,world!".getBytes());
           output.flush();//对添加内容的文件进行更新操作
        }catch (IOException e){
            e.printStackTrace();
        }
    }

在文件进行追加的写法:

 public static void main(String[] args) {
        //文件字节输出流
        try( FileOutputStream output = new FileOutputStream("test.txt")true){//true表示开始追加模式
           output.write("lb".getBytes());
           output.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

文件拷贝

文件的输入流InputStream 和输出流OutputStream 可以实现文件的拷贝

public static void main(String[] args) {
        //文件拷贝
        //目标文件www.txt不存在时,系统会自动建
        try( FileInputStream in = new FileInputStream("test.txt");
             FileOutputStream out = new FileOutputStream("www.txt")){
            int n;
            while ((n = in.read()) != -1){
                out.write(n);
            }
            output.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值