Java实现文件复制的四种方式

背景:有很多的Java初学者对于文件复制的操作总是搞不懂,下面我将用4中方式实现指定文件的复制。

实现方式一:使用FileInputStream/FileOutputStream字节流进行文件的复制操作

 1 private static void streamCopyFile(File srcFile, File desFile) throws IOException {
 2         // 使用字节流进行文件复制
 3         FileInputStream fi = new FileInputStream(srcFile);
 4         FileOutputStream fo = new FileOutputStream(desFile);
 5         Integer by = 0;
 6         //一次读取一个字节
 7         while((by = fi.read()) != -1) {
 8             fo.write(by);
 9         }
10         fi.close();
11         fo.close();
12     }

实现方式二:使用BufferedInputStream/BufferedOutputStream高效字节流进行复制文件

 1 private static void bufferedStreamCopyFile(File srcFile, File desFile) throws IOException {
 2         // 使用缓冲字节流进行文件复制
 3         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
 4         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile));
 5         byte[] b = new byte[1024];
 6         Integer len = 0;
 7         //一次读取1024字节的数据
 8         while((len = bis.read(b)) != -1) {
 9             bos.write(b, 0, len);
10         }
11         bis.close();
12         bos.close();
13     }

实现方式三:使用FileReader/FileWriter字符流进行文件复制。(注意这种方式只能复制只包含字符的文件,也就意味着你用记事本打开该文件你能够读懂)

 1 private static void readerWriterCopyFile(File srcFile, File desFile) throws IOException  {
 2         // 使用字符流进行文件复制,注意:字符流只能复制只含有汉字的文件
 3         FileReader fr = new FileReader(srcFile);
 4         FileWriter fw = new FileWriter(desFile);
 5         
 6         Integer by = 0;
 7         while((by = fr.read()) != -1) {
 8             fw.write(by);
 9         }
10         
11         fr.close();
12         fw.close();
13     }

实现方式四:使用BufferedReader/BufferedWriter高效字符流进行文件复制(注意这种方式只能复制只包含字符的文件,也就意味着你用记事本打开该文件你能够读懂)

 1 private static void bufferedReaderWriterCopyFile(File srcFile, File desFile)  throws IOException {
 2         // 使用带缓冲区的高效字符流进行文件复制
 3         BufferedReader br = new BufferedReader(new FileReader(srcFile));
 4         BufferedWriter bw = new BufferedWriter(new FileWriter(desFile));
 5         
 6         char[] c = new char[1024];
 7         Integer len = 0;
 8         while((len = br.read(c)) != -1) {
 9             bw.write(c, 0, len);
10         }
11         
12         //方式二
13         /*String s = null;
14         while((s = br.readLine()) != null) {
15             bw.write(s);
16             bw.newLine();
17         }*/
18         
19         br.close();
20         bw.close();
21     }

以上便是Java中分别使用字节流、高效字节流、字符流、高效字符流四种方式实现文件复制的方法!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值