Day09_11目标:文件字节输出流

目标:文件字节输出流

IO流的体系:

​ 字节流 字符流
字节输入流 字节输出流 字符输入流 字符输出流
InputStream OutputStream Reader Writer (抽象类)
FileInputStream FileOutputStream FileReader FileWriter (实现类)

b.文件字节输出流:FileOutputStream

​ – 作业:以内存为基准,把内存中的数据以字节的形式写出到磁盘文件中去。写数据到文件中去。
​ – 构造器:
​ public FileOutputStream(File file)
​ public FileOutputStream(String pathName)
​ public FileOutputStream(File file ,boolean append)
​ public FileOutputStream(String pathName ,boolean append)
​ – 方法:
​ public void write(int b):写一个字节出去。
​ public void write(byte[] buffer):写一个字节数组出去。
​ public void write(byte[] buffer,int pos,int len):写一个字节数组的一部分出去。
​ 参数一:字节数组。
​ 参数二:从哪个字节索引开始
​ 参数三:写多少个字节出去
字节输出流:默认写数据的时候会覆盖之前全部的数据。

public class FileOutputStreamDemo01 {
    public static void main(String[] args) throws Exception {
        // 1.创建一个目标文件对象
        File f = new File("src/dlei06.txt");
        // 2.创建一个字节输出流管道与目标文件接通
        OutputStream os = new FileOutputStream(f);
        // 3.写一个字节出去。
        os.write(97); // 字节a
        os.write('b'); // 字节b

        // 4.写一个字节数组出去
        // 把字符串按照当前默认代码编码转换成字节数组。
        byte[] buffer = "我爱你中国abc".getBytes();
        // 按照指定的编码把中文转换成字节数组。
        //byte[] buffer = "我爱你中国abc".getBytes("GBK");
        os.write(buffer);

        // 5.写一个字节数组的一部分出去。
        byte[] buffer1 = "我爱你中国abc".getBytes();
        os.write(buffer1,0,15);

        // os.flush(); // 刷新数据,让数据立即进入文件中去!刷新后管道可以继续使用。
        os.close(); // 关闭管道,关闭包含刷新,关闭后流不可再使用。
    }
}

字节输出流追加数据的管道:第二个参数填写true即可。
OutputStream os = new FileOutputStream(“src/dlei07.txt”,true);
换行: os.write("\r\n".getBytes()); // 换行!

public class FileOutputStreamDemo02 {
    public static void main(String[] args) throws Exception {
        // 1.创建一个字节输出流管道与目标文件路径接通
        // 简化写法:
        // OutputStream os = new FileOutputStream("src/dlei07.txt");

        /**
         * 参数一:文件路径
         * 参数二:true 追加管道,写数据不会覆盖,只会在文件后面追加数据。
         */
        OutputStream os = new FileOutputStream("src/dlei07.txt",true);
        // 2.写一个字节出去。
        os.write(97); // 字节a
        os.write('b'); // 字节b
        os.write("\r\n".getBytes()); // 换行!

        // 3.写一个字节数组出去
        // 把字符串按照当前默认代码编码转换成字节数组。
        byte[] buffer = "我爱你中国abc".getBytes();
        // 按照指定的编码把中文转换成字节数组。
        //byte[] buffer = "我爱你中国abc".getBytes("GBK");
        os.write(buffer);
        os.write("\r\n".getBytes()); // 换行!

        // 4.写一个字节数组的一部分出去。
        byte[] buffer1 = "我爱你中国abc".getBytes();
        os.write(buffer1,0,15);
        os.write("\r\n".getBytes()); // 换行!

        // os.flush(); // 刷新数据,让数据立即进入文件中去!刷新后管道可以继续使用。
        os.close(); // 关闭管道,关闭包含刷新,关闭后流不可再使用。
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值