java io流复制文件代码
时间: 2024-04-14 16:21:33 浏览: 97
Java IO流复制文件的代码可以使用字符流或字节流实现。下面分别介绍两种方式的代码实现:
1. 使用字符流实现文件复制:
```
public static void copyFileByChar(String sourcePath, String targetPath) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader(sourcePath);
out = new FileWriter(targetPath);
char[] buffer = new char[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
```
2. 使用字节流实现文件复制:
```
public static void copyFileByByte(String sourcePath, String targetPath) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(sourcePath);
out = new FileOutputStream(targetPath);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
```
以上两种方式都是通过读取源文件,然后将读取到的内容写入目标文件实现文件复制。其中,字符流适用于文本文件的复制,而字节流适用于任意类型的文件复制。
阅读全文