当前位置: 首页> 健康> 美食 > [java][代码]java复制文件的三种方式

[java][代码]java复制文件的三种方式

时间:2025/7/29 15:27:53来源:https://blog.csdn.net/awonw/article/details/141729019 浏览次数:0次
package cn.dj.io;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;/*** 文件的复制* @author Administrator**/
public class CopyFileDemo {/*** @param args* @throws IOException*/public static void main(String[] args) throws IOException {// TODO Auto-generated method stubcopy_2();}/* * method_3* @throws IOException*/public static void copy_3() throws IOException {// TODO Auto-generated method stubFileInputStream fis = new FileInputStream("c:\\0.ape");BufferedInputStream bufis = new BufferedInputStream(fis);FileOutputStream fos = new FileOutputStream("c:\\3.ape");BufferedOutputStream bufos = new BufferedOutputStream(fos);int ch = 0;while ((ch = bufis.read()) != -1) {bufos.write(ch);}bufos.close();bufis.close();}/*** method_2* @throws IOException* @author Administrator***/public static void copy_2() throws IOException {// TODO Auto-generated method stubFileInputStream fis = new FileInputStream("c:\\0.ape");BufferedInputStream bufis = new BufferedInputStream(fis);FileOutputStream fos = new FileOutputStream("c:\\2.ape");BufferedOutputStream bufos = new BufferedOutputStream(fos);byte[] buf = new byte[1024];int len = 0;while ((len = bufis.read(buf)) != -1) {bufos.write(buf, 0, len);}bufos.close();bufis.close();}/*** method_1* @throws IOException*/public static void copy_1() throws IOException {// TODO Auto-generated method stubFileInputStream fis = new FileInputStream("c:\\0.ape");FileOutputStream fos = new FileOutputStream("c:\\1.ape");byte[] buf = new byte[1024];int len = 0;while ((len = fis.read(buf)) != -1) {fos.write(buf, 0, len);}fos.close();fis.close();}
}

这段Java代码演示了三种不同的方法来复制文件。每个方法都使用了不同的I/O流来实现文件的读取和写入。下面是对每个方法的解释:

方法1: copy_1()

  • 使用FileInputStream来读取源文件。
  • 使用FileOutputStream来写入目标文件。
  • 定义了一个缓冲区buf,大小为1024字节。
  • 在一个循环中,使用read方法从源文件读取数据到缓冲区,然后使用write方法将缓冲区的数据写入目标文件。
  • 循环直到读取操作返回-1,表示文件末尾。
  • 最后关闭了输入和输出流。

方法2: copy_2()

  • 与方法1类似,但增加了BufferedInputStreamBufferedOutputStream来提供缓冲功能,这可以提高文件读写的效率。
  • 同样使用了一个1024字节的缓冲区。
  • 循环中使用read方法从源文件读取数据到缓冲区,然后使用write方法将缓冲区的数据写入目标文件。
  • 循环直到读取操作返回-1。
  • 最后关闭了输入和输出流。

方法3: copy_3()

  • 使用FileInputStreamFileOutputStream来处理文件读写。
  • 使用BufferedInputStreamBufferedOutputStream来提供缓冲。
  • 没有使用缓冲区数组,而是直接在循环中读取单个字符并写入目标文件。
  • 循环直到读取操作返回-1。
  • 最后关闭了输入和输出流。
关键字:[java][代码]java复制文件的三种方式

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: