这是我的代码:
int lines = 0;
br.mark(0);
while (br.readLine() != null) lines++;
System.out.print(lines);
br.reset();
我正在尝试弄清输入文件中的行数,然后将其重置回顶部,因此以后在代码中不会出现错误。我认为可以使用标记和重置方法。另外,我的文件相对较小,从其他答案中我得知,如果文件太大,可能会出现问题。我对这些用法的用法不正确吗?这是我得到的错误:
Exception in thread "main" java.io.IOException: Mark invalid
at java.io.BufferedReader.reset(BufferedReader.java:512)
at Main.main(Main.java:12)
尝试一下:
int lines= (int) Files.lines(Paths.get(fileName)).count();
或
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {
//br returns as stream and convert it into a List
lines = (int) br.lines().count()
} catch (IOException e) {
e.printStackTrace();
}
SpringApplication.run(QuicksilverApplication.class, args);
}