- import java.io.*;
-
- public class FileCopier {
- public static void main(String[] args) {
- String sourcePath = "C:\\a.jpg"; // 源文件路径
- String destinationPath = "E:\\a.jpg"; // 目标文件路径
-
- copyFile(sourcePath, destinationPath);
-
- System.out.println("文件复制完成。");
- }
-
- public static void copyFile(String sourcePath, String destinationPath) {
- try (InputStream inputStream = new FileInputStream(sourcePath);
- OutputStream outputStream = new FileOutputStream(destinationPath)) {
-
- int byteRead;
-
- while ((byteRead = inputStream.read()) != -1) {
- outputStream.write(byteRead);
- }
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
在上面的示例中,我们创建了一个 FileInputStream 来读取源文件,创建了一个 FileOutputStream 来写入目标文件。通过每次读取一个字节并将其写入输出流的方式,实现了文件的复制。最后,我们将源文件路径和目标文件路径传递给 copyFile 方法来执行文件复制操作。
同样的,我们使用了 try-with-resources 语句来自动关闭输入流和输出流,以确保资源被正确释放。
记得将 sourcePath 和 destinationPath 替换为你实际的文件路径。