【发布时间】:2020-04-08 11:53:15
【问题描述】:
我正在尝试读取txt 文件并显示文件元素。我想在同一行显示元素以给出一个换行符。但是,当文件中的新行开始时,给出额外的新行。 txt 文件是:
星际 % Christopher Nolan % 2014 % PG-13
开始 % Christopher Nolan % 2010 % PG-13
Endgame % Russo Brothers % 2019 % PG-13
这里,% 是分隔符。到目前为止我做了什么:
File file_path = new File("film.txt");
try {
Scanner file_input = new Scanner(file_path);
file_input.useDelimiter("%");
for(new_book=1; file_input.hasNext(); new_book++) {
String book_item = file_input.next().trim();
System.out.println(book_item);
if(new_book%4==0){
System.out.println();
}
}
file_input.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
它提供了什么:
Interstellar
Christopher Nolan
2014
PG-13
Inception
Christopher Nolan
2010
PG-13
Endgame
Russo Brothers
2019
PG-13
我想要的是:
Interstellar
Christopher Nolan
2014
PG-13
Inception
Christopher Nolan
2010
PG-13
我注意到的是,在行尾索引不起作用,即如果我打印 new_book 那么,new_book 值不会显示在第一个和第二个 PG-13 中,但显示在最后一个 PG-13 .
我对文件中的这一行感到困惑。每一个建议都值得赞赏!!!另外,请注意,我不会与语法错误混淆。但是,与逻辑和文件读取过程是如何完成的。
【问题讨论】:
-
这真的是您使用的代码吗?
-
是的,我认为它会起作用。
-
我认为您没有运行此代码。它缺少结束
}并使用-作为分隔符。它可能在其他方面也与您的真实代码不同。您能否发布一个说明问题的自包含示例? -
现在我已经编辑了...谢谢...
标签: java file line file-handling