Java编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下: 使用FileInputStream、FileOutputStreaem和FileReader、FileWriter分别进行拷贝。
时间: 2025-02-09 10:16:48 浏览: 39
好的,我很乐意为您提供一个Java程序,使用字节流和字符流分别拷贝文本文件的示例。以下是满足您要求的代码:
```java
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
String sourcePath = "source.txt";
String destPathByte = "dest_byte.txt";
String destPathChar = "dest_char.txt";
// 使用字节流拷贝文件
copyFileByByteStream(sourcePath, destPathByte);
// 使用字符流拷贝文件
copyFileByCharStream(sourcePath, destPathChar);
System.out.println("文件拷贝完成!");
}
// 使用字节流拷贝文件的方法
public static void copyFileByByteStream(String source, String dest) {
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 使用字符流拷贝文件的方法
public static void copyFileByCharStream(String source, String dest) {
try (FileReader fr = new FileReader(source);
FileWriter fw = new FileWriter(dest)) {
char[] buffer = new char[1024];
int length;
while ((length = fr.read(buffer)) != -1) {
fw.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个程序实现了以下功能:
1. 定义了源文件路径和目标文件路径。
2. 使用字节流(FileInputStream和FileOutputStream)拷贝文件到dest_byte.txt。
3. 使用字符流(FileReader和FileWriter)拷贝文件到dest_char.txt。
4. 两种方法都使用了缓冲数组来提高效率。
5. 使用try-with-resources语句来确保文件流在使用后被正确关闭。
6. 捕获并处理了可能的IOException异常。
这个程序展示了字节流和字符流在文件拷贝中的应用。字节流适用于所有类型的文件,而字符流更适合处理文本文件。选择使用哪种流取决于具体的应用场景和需求。
阅读全文
相关推荐















