IO流——将给定路径下文件的内容复制到指定路径的另一个文件里

如题,运用IO流的知识将给定路径下文件的内容复制到指定路径的另一个文件里。

思考步骤:

  1. 打开读写流
  2. 进行读写
  3. 关闭读写流

代码实现:

public class Demo {

    public static void read()throws FileNotFoundException,IOException {
       String path = "C:\\Users\\50579\\Desktop\\tt.txt";  //源文件路径
       String path1 = "C:\\Users\\50579\\Desktop\\aa.txt"; //目的文件路径
        FileInputStream  fileInputStream = new FileInputStream(path);  //用FileInputStream进行读
        FileOutputStream fileOutputStream = new FileOutputStream(path1) ;   //FileOutputStream写


        //方法1
       int byt = 0;   //定义一个值,用来判断读的位置
        while ((byt = fileInputStream.read()) != -1){  //用输入流读源文件,若byt等于-1表示读到文件内容结尾处,则退出循环
        fileOutputStream.write(byt);  //用输出流将读到的数据写入目的文件
        }

      //方法2
        byte[] bytes = new byte[100];
        while ((byt = fileInputStream.read(bytes))!= -1){
            fileOutputStream.write(bytes,0, byt);
        }

        //错误方法3(会导致文件内容丢失一半)
        while(fileInputStream.read()!= -1){
            fileOutputStream.write(fileInputStream.read());
        }
        //错误方法4(文件大小受限:若文件太大,则太浪费CPU资源)
          fileInputStream.read(bytes);
          fileOutputStream.write(bytes);


        fileInputStream.close();  //关闭输入流
        fileOutputStream.close(); //关闭输出流
    }
    public static void main(String[] args) {
        try {
            read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

实现结果:

源文件的内容:(在读取之前目的文件为空或者不存在)
在这里插入图片描述
运行程序:(目的路径下通过字节输出流的write方法新建了一个文件aa.txt)
在这里插入图片描述
打开aa.txt,显示内容和tt.txt内容一样,实现了文件内容的复制功能
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值