我有一个简单的函数来读取文件,但是它只读取行,并且在读取每一行的内容之前,我希望它已经存在,所以我已经有了文件中行的总值。
try {
FileReader leitor = new FileReader("config.txt");
//file to reade
BufferedReader buffer = new BufferedReader(leitor, 2 * 1024 * 1024);
String linha = buffer.readLine();
while (linha != null) {
//I want to do an "if" here to get the value of the last line of the file and save in a variable.
System.out.print(linha + "\n");
linha = buffer.readLine();
Thread.sleep(1000);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (
IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
谢谢。
答案 0 :(得分:0)
实施long count = buffer.lines().Count();
时,我得到了文件的行数,但由于line = buffer.readLine();
不再起作用,因此计数后它无法继续前进到下一行。
然后我在下面找到了解决方法
//get the path of file
Path path = Paths.get("./config.txt");
//count the lines number
int linesNumber = ((int) Files.lines(path).count());