1. 使用字符流BufferedReader类,将一个文本文件Test6_1.txt的内容按行读出,每读出一行就顺序添加行号,并写入到另一个新文件Test6_2中。2.7、 使用字符流BufferedReader和BufferedWriter类,实现将2个文件合并成一个文件,文件名由控制台输入。
时间: 2024-03-04 17:49:42 浏览: 70
好的,以下是 Java 代码实现:
1. 使用 `BufferedReader` 和 `BufferedWriter` 读写文件并添加行号:
```java
import java.io.*;
public class Test {
public static void main(String[] args) {
String inputFileName = "Test6_1.txt";
String outputFileName = "Test6_2.txt";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(inputFileName));
bw = new BufferedWriter(new FileWriter(outputFileName));
String line;
int lineNumber = 1;
while ((line = br.readLine()) != null) {
bw.write(String.format("%d: %s\n", lineNumber, line));
lineNumber++;
}
System.out.println("文件写入成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
2. 使用 `BufferedReader` 和 `BufferedWriter` 合并两个文件:
```java
import java.io.*;
public class Test {
public static void main(String[] args) {
BufferedReader br1 = null;
BufferedReader br2 = null;
BufferedWriter bw = null;
try {
// 从控制台输入合并后的文件名
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入合并后的文件名:");
String outputFileName = console.readLine();
// 读取第一个文件
String inputFileName1 = "test1.txt";
br1 = new BufferedReader(new FileReader(inputFileName1));
// 读取第二个文件
String inputFileName2 = "test2.txt";
br2 = new BufferedReader(new FileReader(inputFileName2));
// 写入合并后的文件
bw = new BufferedWriter(new FileWriter(outputFileName));
String line;
while ((line = br1.readLine()) != null) {
bw.write(line + "\n");
}
while ((line = br2.readLine()) != null) {
bw.write(line + "\n");
}
System.out.println("文件合并成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (br1 != null) {
br1.close();
}
if (br2 != null) {
br2.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
注意:以上两个代码中都有关闭流的操作,以确保资源能够正确释放。
阅读全文