java字节流字符流复制文件
时间: 2023-12-18 08:29:42 浏览: 120
在Java中,字节流和字符流都可以用来复制文件。下面是使用字节流和字符流分别复制文件的示例代码:
1. 使用字节流复制文件
```java
import java.io.*;
public class ByteStreamCopy {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("source.txt");
FileOutputStream fos = new FileOutputStream("target.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 使用字符流复制文件
```java
import java.io.*;
public class CharacterStreamCopy {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("source.txt");
FileWriter fw = new FileWriter("target.txt");
char[] buffer = new char[1024];
int len;
while ((len = fr.read(buffer)) > 0) {
fw.write(buffer, 0, len);
}
fr.close();
fw.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文