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


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

 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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM