java - Java读写文件和添加行号

标签 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);
      }
   }
}

谢谢,感谢您的帮助。

最佳答案

我会推荐 BufferedReader(当然)和 PrintWriter。与 BufferedWriter 相比,PrintWriter 是一个更丰富的 API。

关于java - Java读写文件和添加行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016242/

相关文章:

Java EE war 部署或重新部署 - 自动选择适当的操作

python - 在 python 中将堆栈信息添加到日志格式

c++ - 模逆算法

javascript - 如何正确排序整数数组

java - 日期格式 : month abbreviation with dot

java - Spring 是否使 SecurityContext 可用于执行 Hystrix 命令的线程

java - 多行文本区域的正则表达式

c - 没有 fflush(stdout) 输出不打印

haskell - 使用Data.Binary.decodeFile,遇到错误 "demandInput: not enough bytes"

java - 使用 Gson 从 JSON 字符串中提取正确格式的数字