用Java读取/写入文件并添加行号

时间:2013-06-10 02:45:37

标签: java io numbers try-catch copy-paste

我有以下任务要完成:

写了一个读取文件的程序,并将该文件的副本写入另一个插入了行号的文件。

到目前为止,我编写了下面发布的代码。此代码读取文本并将其复制到另一个文件,但我无法弄清楚如何为新文本文件中的每一行编号。有人可以告诉我如何这样做吗?

import java.io.*;

class FileCopy
{
   public static void main(String[] args) 
   {
      try 
      {
         File fileIn  = new File("Assign4.txt");
         File fileOut = new File("target.txt");

         FileInputStream streamIn   = new FileInputStream(fileIn);
         FileOutputStream streamOut = new FileOutputStream(fileOut);

         int c;
         while ((c = streamIn.read()) != -1) 
         {
            streamOut.write(c);
         }

         streamIn.close();
         streamOut.close();
      }
      catch (FileNotFoundException e) 
      {
         System.err.println("FileCopy: " + e);
      } 
      catch (IOException e) 
      {
         System.err.println("FileCopy: " + e);
      }
   }
}

谢谢,感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我会建议BufferedReader(肯定)和PrintWriter。与BufferedWriter相比,PrintWriter是一个更丰富的API。

答案 1 :(得分:-1)

您可以BufferedReaderBufferedReader来读写文本文件:

BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
BufferedWriter writer = new BufferedWriter( new FileWriter("target.txt"));
    try {
        int count = 1;  
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();            
        while (line != null) {
            sb.append(count++);
            sb.append(line);
            sb.append("\n");
            writer.write(line);
            line = br.readLine();    
        }
    } finally {
        br.close();
        writer.close();
    }