1.使用Java的输入、输出流将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。
时间: 2024-12-28 10:41:34 浏览: 8
在Java中,你可以使用FileInputStream和FileOutputStream来处理文本文件的输入和输出,`BufferedReader`用于逐行读取,`PrintWriter`或`BufferedWriter`用于按行写入并添加行号。以下是简单的步骤:
1. 首先,你需要导入必要的包:
```java
import java.io.*;
```
2. 定义两个File对象,分别表示源文件和目标文件:
```java
File inputFile = new File("source.txt");
File outputFile = new File("output.txt");
```
3. 创建输入和输出流对象,并打开它们:
```java
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
//...
} catch (IOException e) {
System.err.println("Error reading or writing file: " + e.getMessage());
}
```
4. 使用`BufferedReader`逐行读取,每读取一行就添加行号:
```java
int lineNumber = 1;
String line;
while ((line = reader.readLine()) != null) {
writer.write(lineNumber++ + ": " + line);
writer.newLine(); // 添加换行符
}
```
5. 最后记得关闭流以释放资源:
```java
writer.close();
```
完整代码示例:
```java
import java.io.*;
public class Main {
public static void main(String[] args) {
File inputFile = new File("source.txt");
File outputFile = new File("output.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
int lineNumber = 1;
String line;
while ((line = reader.readLine()) != null) {
writer.write(lineNumber++ + ": " + line);
writer.newLine();
}
} catch (IOException e) {
System.err.println("Error reading or writing file: " + e.getMessage());
}
}
}
```
阅读全文