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中分别使用字节流、高效字节流、字符流、高效字符流四种方式实现文件复制的方法!

posted @   阿豪聊干货  阅读(3195)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示