import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyExample {
public static void copyFile(String sourceFile, String destFile) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(sourceFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
String sourceFile = "source.txt";
String destFile = "destination.txt";
copyFile(sourceFile, destFile);
}
}
这段代码展示了如何在Java中实现文件的拷贝。它使用`FileInputStream`来读取源文件,并使用`FileOutputStream`将读取到的数据写入到目标文件。通过字节缓冲区(这里使用1024字节的缓冲区)来提高拷贝效率。在`finally`块中确保无论拷贝是否成功,都能正确关闭输入流和输出流,以释放系统资源。