在 Java 里,FileChanneljava.nio 包中的一个强大工具,可用于文件的读写操作,借助它能高效地实现文件的复制和移动。

下面为你详细介绍如何使用 FileChannel 实现这两个功能:

使用 FileChannel 实现文件复制

借助 FileChanneltransferFrom()transferTo() 方法可以高效地在通道间传输数据,从而实现文件复制。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileCopyWithFileChannel {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("source.txt");
FileOutputStream fos = new FileOutputStream("target.txt");
FileChannel sourceChannel = fis.getChannel();
FileChannel targetChannel = fos.getChannel()) {
// 使用 transferFrom 方法复制文件
targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
System.out.println("文件复制成功");
} catch (IOException e) {
System.err.println("文件复制失败: " + e.getMessage());
}
}
}    

代码解释

1、创建输入输出流和通道

  • FileInputStream 用于读取源文件,FileOutputStream 用于写入目标文件。
  • 通过 getChannel() 方法分别获取源文件和目标文件的 FileChannel 对象。

2、使用 transferFrom() 方法复制文件

  • transferFrom() 方法将源通道的数据传输到目标通道。
  • 第一个参数是源通道,第二个参数是目标通道的起始位置,第三个参数是要传输的字节数。

3、异常处理

  • 使用 try-with-resources 语句确保资源自动关闭
  • 同时捕获并处理可能出现的 IOException 异常

使用 FileChannel 实现文件移动

文件移动本质上是先复制文件,再删除源文件。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileMoveWithFileChannel {
public static void main(String[] args) {
File sourceFile = new File("source.txt");
File targetFile = new File("target.txt");
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
FileChannel sourceChannel = fis.getChannel();
www.cppcns.com       FileChannel targetChannel = fos.getChannel()) {
// 使用 transferFrom 方法复制文件
targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
// 删除源文件
if (sourceFile.delete()) {
System.out.println("文件移动成www.cppcns.com功");
} else {
KSRZayIer   System.err.println("源文件删除失败");
}
} catch (IOException e) {
System.err.println("文件移动失败: " + e.getMessage());
}
}
}

代码解释

1)创建文件对象和通道:创建 File 对象表示源文件和目标文件,然后创建输入输出流和对应的 FileChannel 对象。

2)复制文件:使用 transferFrom() 方法将源文件的数据复制到目标文件。

3)删除源文件:调用 File 对象的 delete() 方法删除源文件,根据返回结果判断是否删除成功。

4)异常处理:使用 try-with-resources 语句确保资源自动关闭,同时捕获并处理可能出现的 IOException 异常。

注意事项

需要把 "source.txt""t编程客栈arget.txt" 替换为实际的文件路径。