分别使用字节流和字符流拷贝一个文本文件
时间: 2024-05-09 15:14:44 浏览: 107
使用字节流拷贝一个文本文件:
```java
import java.io.*;
public class ByteStreamCopy {
public static void main(String[] args) {
try (InputStream in = new FileInputStream("source.txt");
OutputStream out = new FileOutputStream("target.txt")) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
System.out.println("Copy completed!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用字符流拷贝一个文本文件:
```java
import java.io.*;
public class CharacterStreamCopy {
public static void main(String[] args) {
try (Reader reader = new FileReader("source.txt");
Writer writer = new FileWriter("target.txt")) {
char[] buffer = new char[1024];
int len;
while ((len = reader.read(buffer)) != -1) {
writer.write(buffer, 0, len);
}
System.out.println("Copy completed!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
两个程序都可以将 `source.txt` 文件复制到 `target.txt` 文件。区别在于,字节流是以字节为单位进行操作,而字符流是以字符为单位进行操作。对于文本文件的复制,使用字符流更加方便。
阅读全文