首先,我们需要确保源文件存在且可读。如果源文件不存在或无法访问,则应抛出相应的异常提示用户。接着,打开目标文件进行写入操作,并将源文件的内容逐块读取并写入目标文件,以避免一次性加载大文件导致内存不足的问题。
下面是一个简单的示例代码:
```java
public class Test {
public void copyFile(String sourcePath, String targetPath) {
// 检查源文件是否存在
File sourceFile = new File(sourcePath);
if (!sourceFile.exists()) {
throw new IllegalArgumentException("Source file does not exist: " + sourcePath);
}
// 确保源文件是可读的
if (!sourceFile.canRead()) {
throw new IllegalArgumentException("Cannot read the source file: " + sourcePath);
}
try (InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(targetPath)) {
byte[] buffer = new byte[1024];
int length;
// 从输入流中读取数据,并写入输出流
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch (IOException e) {
System.err.println("An error occurred during file copying: " + e.getMessage());
e.printStackTrace();
}
}
}
```
解释:
1. 检查文件是否存在和可读性:在尝试读取文件之前,我们先检查源文件是否存在以及是否可以被读取。
2. 使用流处理文件:通过 `FileInputStream` 和 `FileOutputStream` 来处理文件的读取与写入。这样可以有效管理资源,并且支持大文件的处理。
3. 缓冲区:使用一个大小为 1024 字节的缓冲区来存储数据,减少频繁的 I/O 操作,提高效率。
4. 异常处理:对于可能发生的 I/O 异常进行了捕获和处理,确保程序不会因为意外情况而崩溃。
通过这种方式,我们可以安全地完成文件的复制操作,同时保持代码的简洁性和健壮性。


