【思路】将文件中的内容按行读取存入一个字符串中,在输出时再为每一行加上行号。
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 }