阅读线每隔一行跳过
问题描述:
我正在制作一个基本上从txt文件加载的小程序。该txt文件具有以下数据:阅读线每隔一行跳过
NAME1, xx, xx, xx, xx (Where XX are numbers)
NAME2, xx, xx, xx, xx
etc...
该文件没有设置结束,因为它可以稍后编辑以添加其他名称。 我要读它的代码如下:
private void doLoadProfile() {
String filePath = System.getProperty("user.dir") + File.separator + "profiles.txt";
System.out.println(filePath);
try {
FileInputStream fis = new FileInputStream(filePath);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
while (in.readLine() != null) {
displayLog.appendText(in.readLine() + "\n");
}
} catch (FileNotFoundException e) {
displayLog.appendText("\n Error: file not found" + e.toString());
} catch (IOException e) {
displayLog.appendText("\n Error: " + e.toString());
}
}
然而,这只是所有其他线路输出,由于某种原因,它跳过线(我有一个txt文件,4号线,我只得到了第2和第4线)。我尝试添加额外的2条线,并再次获得第2,第4和第6。
答
您正在调用in.readLine()两次(一次在while语句中读取第一行,再次在appendText中读取第二行)。在字符串中缓存while语句中的值,然后使用它。
每个'readLine'调用遍历到下一行并返回它,也是在'while'条件中的一个。您需要阅读一次,存储在变量中,并在需要时使用变量。现在,重复的地方(使用googling for'java readline跳过行'可能与'site:*.com'结果来自这个网站)。 – Pshemo
那么,你每次迭代调用readLine()两次。别。调用一次,将结果存储在一个变量中,检查它是否为空,然后追加它。或者使用readAllLines(https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-) –