java三种复制文件方法
时间: 2023-11-12 15:08:55 浏览: 122
Java中有以下三种复制文件的方法:
1. 使用FileInputStream和FileOutputStream类
使用FileInputStream读取源文件,然后使用FileOutputStream将读取的数据写入目标文件。
```
public static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
```
2. 使用Files.copy()方法
Java 7引入了Files.copy()方法,可以使用它来复制文件。
```
public static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
```
3. 使用Apache Commons IO库
Apache Commons IO库提供了一个FileUtils类,其中有一个copyFile()方法,可以用于复制文件。
```
public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
```
阅读全文
相关推荐










