我正在尝试从Java属性文件中获取2D数组数据,并将这些数据存储到HashMap对象中。让我感到困惑的是,Eclipse只从2D数组中检索到部分数据。
以下是代码:
Properties config = new Properties();
config.load(new FileInputStream("categories.properties"));
String[][] categories = fetchArrayFromPropFile("content", config);
HashMap<String,Integer> hashmap = new HashMap<String,Integer>();
for (String[] mapping : categories)
{
hashmap.put(mapping[0], 0);
}
private static String[][] fetchArrayFromPropFile(String propertyName, Properties propFile) {
String[] a = propFile.getProperty(propertyName).split(";");
String[][] array = new String[a.length][a.length];
for(int i = 0;i < a.length;i++) {
array[i] = a[i].split(",");
}
return array;
}
在类别属性文件中:
content=Advertising,0;Agriculture,0;Art,0;Automotive,0;Aviation,0;Banking,0;Beverages,0;Biotechnology,0;Business,0;Crime,0;Disasters,0;Economics,0;Education,0;Elections,0;Fashion,0;Food,0;Hardware,0;Health,0;Hotels,0;Intellectual Property,0;Investing,0;Labor,0;
Law,0;Marriage,0;Mobile Devices,0;Politics,0;Real Estate,0;Renewable Energy,0;Robotics,0;Science,0;Social Media,0;Software and Internet,0;Space,0;Sports,0;Technology,0;Traditional Energy,0;Travel,0;Video Games,0;War,0;Weather,0;Entertainment,0;No Topic,0; Business_Finance,0;Disaster_Accident,0;Entertainment_Culture,0;Environment,0;Health_Medical_Pharma,0;Hospitality_Recreation,0;Human Interest,0;Law_Crime,0;Religion_Belief,0;Technology_Internet,0;War_Conflict,0;Other,0;
这是因为您的属性文件格式是
content=XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
你看,它被分成两行用于一个属性。因此,在读取内容属性时,它只读取第一行,不包含所有数据。
如果是这样,请像这样手动将您的属性文件连接成一行。
content=Advertising,0;Agriculture,0;Art,0;Automotive,0;Aviation,0;Banking,0;Beverages,0;Biotechnology,0;Business,0;Crime,0;Disasters,0;Economics,0;Education,0;Elections,0;Fashion,0;Food,0;Hardware,0;Health,0;Hotels,0;Intellectual Property,0;Investing,0;Labor,0;Law,0;Marriage,0;Mobile Devices,0;Politics,0;Real Estate,0;Renewable Energy,0;Robotics,0;Science,0;Social Media,0;Software and Internet,0;Space,0;Sports,0;Technology,0;Traditional Energy,0;Travel,0;Video Games,0;War,0;Weather,0;Entertainment,0;No Topic,0; Business_Finance,0;Disaster_Accident,0;Entertainment_Culture,0;Environment,0;Health_Medical_Pharma,0;Hospitality_Recreation,0;Human Interest,0;Law_Crime,0;Religion_Belief,0;Technology_Internet,0;War_Conflict,0;Other,0;
如果是这样,则代码工作正常,并且会读取所有数据。
我想你想要:
String[][] array = new String[a.length][2];
使用 "\" 连接一个属性的不同线。
例如:
a=b
c