【问题标题】:How to add line numbers to a text file?如何在文本文件中添加行号?
【发布时间】:2014-04-11 22:15:17
【问题描述】:

所以我需要编写一个程序来读取包含文本的文件,然后将行号添加到每一行。到目前为止,我打印出了行号,而不是只打印出每一行,而是打印出每一行中的所有文本。我怎样才能让它打印出来呢?

这是我目前的代码:

public static void main(String[] args) throws FileNotFoundException {
    try {
        ArrayList<String> poem = readPoem("src\\P7_2\\input.txt");
        number("output.txt",poem);
    }catch(Exception e){
        System.out.println("File not found.");
    }
}

public static ArrayList<String> readPoem(String filename) throws FileNotFoundException {
    ArrayList<String> lineList = new ArrayList<String>();
    Scanner in = new Scanner(new File(filename));
    while (in.hasNextLine()) {
        lineList.add(in.nextLine());
    }
    in.close();
    return lineList;
}
public static void number (String filename,ArrayList<String> lines) throws FileNotFoundException{
    PrintWriter out = new PrintWriter(filename);
    for(int i = 0; i<lines.size(); i++){
        out.println("/* " + i + "*/" + lines);
    }
    out.close();
}

【问题讨论】:

  • 首先,你使用Java 7吗?它会让你的工作更轻松

标签: java arrays input output


【解决方案1】:

这是使用 Java 7 提供的新功能的程序的较短版本;它假设你有一个足够短的源文件:

final Charset charset = StandardCharsets.UTF_8;
final String lineSeparator = System.lineSeparator();

final Path src = Paths.get("src\\P7_2\\input.txt");
final Path dst = Paths.get("output.txt");

try (
    final BufferedWriter writer = Files.newBufferedWriter(src, charset, StandardOpenOption.CREATE);
) {
    int lineNumber = 1;
    for (final String line: Files.readAllLines(src, charset))
        writer.write(String.format("/* %d */ %s%s", lineNumber++, line, lineSeparator));
    writer.flush();
}

【讨论】:

  • System.lineSeparator()
  • 我认为是在 Java 7 中添加的。 :) 另外,当我仔细观察时,发现您只是在 String.format 中使用它,所以您不妨将%n 放在格式字符串中。
【解决方案2】:

使用

out.println("/* " + i + "*/" + lines.get(i));

代替

out.println("/* " + i + "*/" + lines);

您正在打印每一行的完整列表。

【讨论】:

    【解决方案3】:

    我会说这是你的问题:

    out.println("/* " + i + "*/" + lines); //this prints all the lines each loop execution

    您可以尝试使用:

    int i = 1; //or the first value you wish
    for(String a : lines){
        out.println("/* " + i + "*/" + a);
        i++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-28
      • 2011-12-01
      • 2015-01-08
      • 1970-01-01
      • 2015-12-19
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多