JavaSe之IO流文件输入输出

 一、节点流,使用字符流进行文件的复制

    @Test
    public void test3() {
        FileWriter fileWriter = null;
        FileReader fileReader = null;
        try {
            File file1 = new File("src/demo/s2022/secondPart/stu0729/file/StringFile.txt");//定义源文件(必须存在)
            File file2 = new File("src/demo/s2022/secondPart/stu0729/file/StringFile2.txt");//定义输出文件
            fileReader = new FileReader(file1);
            fileWriter = new FileWriter(file2, true);//true设置为追加,默认false覆盖
            char[] readChar = new char[5];//每次读取5个字符
            int len;//获取的字符个数
            while ((len = fileReader.read(readChar)) != -1) {//-1表示获取到末尾
                System.out.print(readChar);
                fileWriter.write(readChar, 0, len);//写入字符数组里的内容,从索引0到len
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

二、处理流,使用缓冲流对节点流进行包装处理,图片复制

@Test
    public void test() throws IOException {
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            File srcFile = new File("src/demo/s2022/secondPart/stu0729/img/csdn.png");
            File destFile = new File("src/demo/s2022/secondPart/stu0729/img/csdn2.png");
            FileInputStream fileInputStream = new FileInputStream(srcFile);
            FileOutputStream fileOutputStream = new FileOutputStream(destFile);
            bufferedInputStream = new BufferedInputStream(fileInputStream);//对节点流的包装处理
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);//对节点流的包装处理

            byte[] bytes = new byte[5];//定义每次读取五个字节
            int len;//实际读取的字节数
            while ((len = bufferedInputStream.read(bytes)) != -1) {//对上一次读取的字节数判断,是否读取完,并将读取的字节存入字节数组
                bufferedOutputStream.write(bytes, 0, len);//将数据写入文件
                System.out.println(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bufferedOutputStream != null) {
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

注:处理流关闭的同时,字节流也会关闭

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值