文本文件中的hashmap未完全读取

时间:2012-02-27 11:13:47

标签: java hashmap text-files

所以我已经工作了几个小时才拿出这段代码

public class instructorIO
{
    static Map<String, String> instructors;


    public static Map<String, String> getInstructors()
    {
        try
        {
          BufferedReader in = new BufferedReader( new FileReader("instructor.txt"));

             instructors = new LinkedHashMap<String, String>();

             String line;

            while(((line = in.readLine()) != null))
            {
                line = in.readLine();
                String[] val = line.split("<>");
                String ID = val[0];
                String name = val[1];

                instructors.put(ID, name);
            }
            in.close();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }

        return instructors;
    }
}

当我尝试在文本区域中显示所有hashmap值时,仅显示散列ID 2,6和4。总共有6个......我做错了什么?

当我尝试用另一个文本文件执行此操作时,我在线程“main”中得到一个异常java.lang.NullPointerException at String [] val = line.split(“&lt;&gt;”);

3 个答案:

答案 0 :(得分:1)

您一次只读两行,只读第二行:

        while(((line = in.readLine()) != null))
        {
            line = in.readLine();
            String[] val = line.split("<>");
            String ID = val[0];
            String name = val[1];

            instructors.put(ID, name);
        }

一旦处于while状态,再次进入循环体内。我建议你这样做:

        while(((line = in.readLine()) != null))
        {                
            String[] val = line.split("<>");
            String ID = val[0];
            String name = val[1];

            instructors.put(ID, name);
        }

答案 1 :(得分:1)

您正在致电:

line = in.readLine();

两次。一旦进入while循环,一次进入。所以你正在跳过其他每一行。

答案 2 :(得分:0)

您在line = in.readLine()循环中调用while方法两次。

相关问题