简体   繁体   English

从文件读取并存储

[英]read from file and store

I am trying to read a file and store it using hashmap, but there is this error "java.lang.ArrayIndexOutOfBoundsException: 0". 我正在尝试读取文件并使用hashmap存储它,但是出现此错误“ java.lang.ArrayIndexOutOfBoundsException:0”。 My input has two columns separated by space something like Name ID so on with different entries. 我的输入有两列,两列之间用空格隔开,例如名称ID,等等,并带有不同的条目。 Help is appreciated. 感谢帮助。 Thanks. 谢谢。

Input: 输入:

Mary ID
Mary Lastname
Mary Place
Mary DOB
Mary Homepage
Mary Postcode
John ID
John Lastname
John Place
John DOB
John Homepage
John Postcode

Code: 码:

import java.util.*;

class ReadFileAndStoreHashmap {
    public static void main(String[] args)  {
        try{
            Scanner scanner = new Scanner(new FileReader(".txt"));

            HashMap<String, String> map = new LinkedHashMap<String, String>();

            while (scanner.hasNextLine()) {
                String[] columns = scanner.nextLine().split(" ");
                map.put(columns[0], columns[1]);
                System.out.println(map);
            }
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

I would check the line you're attempting to scan. 我会检查您尝试扫描的行。 I suspect it's blank and hence the scanner can't split it as desired. 我怀疑它是空白的,因此扫描仪无法根据需要进行拆分。

I would recommend asserting/checking on the length of the returned array. 我建议断言/检查返回数组的长度。 If it doesn't have 2 elements then you can easily report this and continue or break as desired, whilst reporting to the user what's gojne wrong. 如果它没有2个元素,那么您可以轻松地报告此问题并根据需要继续或中断,同时向用户报告出现了什么问题。

Most likely you have an empty line somewhere (does you file end with a newline? Then there is an empty line after it, probably.) 您很可能在某处有一个空行(文件是否以换行符结尾?然后可能在其后有一个空行。)

add a check like 添加类似的支票

if(columns.length == 2) 

I prefer to use BufferedReader personally. 我更喜欢个人使用BufferedReader。

Here is my suggestion: 这是我的建议:

try {
    String line;
    BufferedReader filestart = new BufferedReader(new FileReader(file));
    for (line = filestart.readLine(); line !=null; line = filestart.readLine()) {

          String[] columns = line.split(" ");
          map.put(columns[0], columns[1]);
          System.out.println(map);

    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Having "line != null" should ensure you can definitely split the line, before you try. 尝试使用“ line!= null”应确保您绝对可以分割行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM