gpt4 book ai didi

java - 如何向文本文件添加行号?

转载 作者:行者123 更新时间:2023-12-01 13:09:15 24 4
gpt4 key购买 nike

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

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

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 提供的新功能的程序的较短版本;它假设您有一个足够短的源文件:

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

关于java - 如何向文本文件添加行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23023472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com