有人能告诉我如何从 java 中的文件中读取每隔一行吗?
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null){
//Do something ..
line = br.readLine()
}
br.close
最佳答案
一种简单的方法是只维护读取行数的计数器:
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (count % 2 == 0) {
// do something with this line
}
++count;
}
但从技术上讲,这仍然会读取文件中的每一行,只是选择处理每隔一行。如果您真的只想读取每一行,那么像 RandomAccessFile
这样的东西可能是必要的。
关于java - 如何从java中的文件中读取每隔两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57694293/