[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