[Java文件操作] 为文本文件添加行号

本文介绍了一个简单的Java程序,该程序可以读取指定文件的内容,并将每一行内容添加行号后保存到新的文件中。通过使用BufferedReader和PrintWriter等类,实现了文件的读取与写入功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【思路】将文件中的内容按行读取存入一个字符串中,在输出时再为每一行加上行号。

 1 import java.io.*;
 2 public class Text {
 3     private String strFinal = "";
 4     public void open(String fileName) {
 5         try {
 6             BufferedReader in = new BufferedReader(new FileReader(fileName));
 7             String s = null;
 8             while ((s = in.readLine()) != null) {
 9                 strFinal = strFinal + s + "\n";
10             }
11             in.close();
12         } catch (IOException e) {
13             System.out.println(e);
14         }
15     }
16     public void save(String fileName){
17         try{
18             BufferedReader in = new BufferedReader(new StringReader(strFinal));
19             PrintWriter out = new PrintWriter(new FileWriter(fileName));
20             int lineCount = 1;
21             String s = null;
22             while((s = in.readLine())!=null){
23                 out.println(lineCount+++": "+s);
24             }
25             in.close();
26             out.close();
27         }catch(IOException e){
28             System.out.print(e);
29         }
30     }
31     public static void main(String args[])throws IOException{
32         Text obj = new Text();
33         obj.open("D:/Java_workspace/Text/src/Text.java");
34         obj.save("E:\\Example\\A.txt");
35     }
36 }

 

转载于:https://www.cnblogs.com/lca1826/p/6498687.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值