IO流 文件的复制方法

IO流 文件的复制方法

文件的复制

1. jdk9后的新方法
try (var dir = new FileInputStream("E:\\ceshi\\b.txt"); var dos = new FileOutputStream("E:\\ceshi1\\a.txt");) {
        dir.transferTo(dos);
        } catch (Exception e) {
            e.printStackTrace();
        }

注意:不能复制目录
在这里插入图片描述

按字节流
//第二种复制方法 按字节
        File f = new File(str);
        FileInputStream fis = new FileInputStream(str);
        byte[] bt = fis.readAllBytes();
        FileOutputStream fos = new FileOutputStream("E:/ceshi1/ab.txt");
        fos.write(bt);
        fos.flush();
        fos.close();
        fis.close();
字节流并非一次取完,因为上一个readAllByte()方法面对文件较大时,可能出现故障

(推荐)

String str = "E:/ceshi/b.txt";
        String tstr = "E:/ceshi1/abces.txt";
        FileInputStream fis = new FileInputStream(str);
        FileOutputStream fios = new FileOutputStream(tstr);
        byte[] bytes = new byte[1024 * 8];
        int len = 0;
        while((len = fis.read(bytes)) >= 0) {
            fios.write(bytes, 0, len);
        }
        fios.flush();
        fios.close();
        fis.close();
    }
一个字节一个字节读
 String str = "E:/ceshi/b.txt";
        String tstr = "E:/ceshi1/abce.txt";
        FileInputStream fis = new FileInputStream(str);
        FileOutputStream fios = new FileOutputStream(tstr);
        while(true){
            int read = fis.read();
            System.out.println(read);
            if (!(read >= 0)) break;
            fios.write(read);
        }
        fios.flush();
        fios.close();
        fis.close();

字符流复制文件

note:FileStream中的第二个参数如果为真那么所有的写操作默认添加,但是没有true的话,调用append方法也是覆盖。

String str = "E:/ceshi/a.txt";
        String tstr = "E:/ceshi1/abce.txt";
        FileReader fileReader = new FileReader(str);
        FileWriter fileWriter = new FileWriter(tstr,true);
        int read;
        while ((read = fileReader.read()) >= 0){
            System.out.println(read);
            fileWriter.write((char) read);
        }
        fileWriter.flush();
        fileReader.close();
        fileWriter.close();

换行操作

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值