编写一个程序,要求从文件“abc.txt”内读出内容后加上行号打印在屏幕上
时间: 2024-02-20 14:00:28 浏览: 70
以下是实现该程序的代码:
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileLineNumbers {
public static void main(String[] args) {
try {
// 创建文件读取对象
FileReader fr = new FileReader("abc.txt");
BufferedReader br = new BufferedReader(fr);
// 读取文件内容并打印
String line = "";
int lineNumber = 1;
while ((line = br.readLine()) != null) {
System.out.println(lineNumber + ": " + line);
lineNumber++;
}
// 关闭文件读取对象
br.close();
fr.close();
} catch (IOException e) {
System.out.println("File not found or cannot be read.");
}
}
}
```
该程序中,我们使用了FileReader和BufferedReader等类来读取文件内容,并在每一行内容前加上行号进行打印。当文件不存在或无法读取时,会捕获IOException异常并打印错误信息。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![ppt](https://img-home.csdnimg.cn/images/20241231044937.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)