有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

读取文本文件的java方法是跳过行

我正在读一个如下所示的文本文件(见下图)

enter image description here


但是当我使用下面的源代码阅读文本文件时。它跳过了一些行(见下图)
注意,它只显示了该序列中的a1、a3、a5、a7

enter image description here

下面是我的代码,它没有做任何特殊的事情,只是读取文本文件并将其保存在地图中

public static Map<String,Boolean> readSaveBoardState(){

    BufferedReader buffRead = null;
    Map<String, Boolean> scannedSavedState = new TreeMap<String, Boolean>();

    try{

        buffRead = new BufferedReader( new FileReader(saveCurrentState));

        String position = buffRead.readLine();

        while (buffRead.readLine() != null){

            String[] splitDash = position.split("-");

            System.out.println(splitDash[0] + " "+ splitDash[1]);
            scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));

            position = buffRead.readLine();
        }
    }catch(IOException ioe){

        ioe.printStackTrace();

    }finally{

        try {
            buffRead.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }       
    return scannedSavedState;
}

我已经看了30分钟了,我仍然不知道为什么它会这样做。有人能帮忙吗谢谢


共 (3) 个答案

  1. # 1 楼答案

    您读取了两行,但只存储了一次值

     while (buffRead.readLine() != null){ // read here and ignore
    
                String[] splitDash = position.split("-");
    
                System.out.println(splitDash[0] + " "+ splitDash[1]);
                scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));
    
                position = buffRead.readLine(); // read here and use
            }
    
  2. # 2 楼答案

    在循环中调用readLine()两次:第一次在while循环条件中,第二次在循环结束时。第一次调用的输出被丢弃,因为它从来不会被分配给任何变量。 这应该是有效的:

    String position = buffRead.readLine();
    while (position != null){
      ...
      position = buffRead.readLine();
    }
    
  3. # 3 楼答案

    在代码中,您阅读了两行,但只使用一行:

       while (buffRead.readLine() != null){ // read a line
    
            String[] splitDash = position.split("-");
    
            System.out.println(splitDash[0] + " "+ splitDash[1]);
            scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));
    
            position = buffRead.readLine();  // read the second line
        }
    

    改为:

      while ((position =buffRead.readLine()) != null){ // read a line
    
            String[] splitDash = position.split("-");
    
            System.out.println(splitDash[0] + " "+ splitDash[1]);
            scannedSavedState.put(splitDash[0], Boolean.parseBoolean(splitDash[1]));
    
        }