如何在文本文件中添加行号?

时间:2014-04-11 22:15:17

标签: java arrays input output

所以我需要创建一个程序来读取包含文本的文件,然后为每一行添加行号。到目前为止,我打印出行号,但不是只打印每行,而是打印每行中的所有文本。我怎么才能把它打印出去?

这是我到目前为止的代码:

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();
}

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

使用

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

取代

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

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

答案 2 :(得分:0)

我会说这是你的问题:

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++;
}