21xrx.com
2025-03-24 06:47:31 Monday
文章检索 我的文章 写文章
Java文件复制方法及实例
2023-06-16 11:20:27 深夜i     5     0
Java 文件复制 IO流 NIO Apache

在Java编程中,经常需要对文件进行复制操作,如将一个文件从一个目录复制到另一个目录,或者将一个文件拷贝到一个新的文件中。本文将介绍Java语言中文件复制的方法及实例。

文件复制方法的实现一般有三种方式:使用Java IO流、使用Java NIO、使用Java Apache Commons IO。下面我们将具体分析这三种方法。

1. 使用Java IO流

Java IO库提供了FileInputStream和FileOutputStream两个类用于文件的读取和写入。可以通过将这两个类结合起来实现文件从源目录到目标目录的复制操作。具体代码如下所示:

public static void copyFileUsingIO(File source, File dest) throws IOException {
  InputStream is = null;
  OutputStream os = null;
  try {
    is = new FileInputStream(source);
    os = new FileOutputStream(dest);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer)) > 0) {
      os.write(buffer, 0, length);
    }
  } finally {
    is.close();
    os.close();
  }
}

2. 使用Java NIO

Java NIO提供了FileChannel和ByteBuffer两个类用于文件的读取和写入。使用它们可以实现更高效的文件复制。具体代码如下所示:

public static void copyFileUsingNIO(File source, File dest) throws IOException {
  FileInputStream fis = new FileInputStream(source);
  FileOutputStream fos = new FileOutputStream(dest);
  FileChannel sourceChannel = fis.getChannel();
  FileChannel destChannel = fos.getChannel();
  try {
    destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
  } finally {
    sourceChannel.close();
    destChannel.close();
    fis.close();
    fos.close();
  }
}

3. 使用Java Apache Commons IO

Java Apache Commons IO是一个开源的Java IO库,提供了很多关于IO操作的功能。它提供了FileUtils类,可以方便地实现文件的复制操作。具体代码如下所示:

public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
  FileUtils.copyFile(source, dest);
}

以上就是Java文件复制的三种方法及其实现。开发者可以根据项目需求选择适合自己的方法。

Commons IO。

  
  

评论区