java如何拷贝照片
使用 Files.copy 方法(Java NIO)
Java NIO 的 Files.copy 方法提供了一种简单高效的文件拷贝方式,适用于照片或其他二进制文件。以下是示例代码:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class PhotoCopy {
public static void main(String[] args) {
Path source = Paths.get("source.jpg");
Path target = Paths.get("target.jpg");
try {
Files.copy(source, target);
System.out.println("照片拷贝成功");
} catch (IOException e) {
System.err.println("拷贝失败: " + e.getMessage());
}
}
}
使用 FileInputStream 和 FileOutputStream
传统的 IO 流方式适用于所有 Java 版本,通过逐字节或缓冲区读写实现拷贝:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class PhotoCopyTraditional {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("source.jpg");
FileOutputStream fos = new FileOutputStream("target.jpg")) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
System.out.println("照片拷贝完成");
} catch (IOException e) {
System.err.println("错误: " + e.getMessage());
}
}
}
使用 BufferedInputStream 提升性能
通过缓冲流减少直接 IO 操作次数,显著提升大文件拷贝效率:
import java.io.*;
import java.nio.file.*;
public class BufferedPhotoCopy {
public static void main(String[] args) {
Path sourcePath = Paths.get("source.jpg");
Path targetPath = Paths.get("target.jpg");
try (InputStream is = new BufferedInputStream(Files.newInputStream(sourcePath));
OutputStream os = new BufferedOutputStream(Files.newOutputStream(targetPath))) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用 Apache Commons IO 库
第三方库 FileUtils 提供单行代码实现文件拷贝,适合快速开发:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class PhotoCopyCommons {
public static void main(String[] args) {
try {
FileUtils.copyFile(
new File("source.jpg"),
new File("target.jpg")
);
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 目标文件存在时,NIO 的
Files.copy会抛出FileAlreadyExistsException,需通过StandardCopyOption.REPLACE_EXISTING参数覆盖 - 大文件建议使用缓冲区(如 8KB 以上)减少 IO 操作次数
- 流操作务必使用 try-with-resources 确保资源释放
- 检查源文件是否存在(
Files.exists(sourcePath))可避免异常






