0

我正在尝试从 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;
}

在 categories.properties 文件中:

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;
4

3 回答 3

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;

如果是这样,您的代码工作正常并且所有数据都被读取。

于 2012-10-02T03:26:25.837 回答
0

使用“\”连接一个属性的不同线。

例如:

  a=b \
    c
于 2012-10-02T03:40:34.900 回答
0

我想你想要:

String[][] array = new String[a.length][2];
于 2012-10-02T03:01:10.033 回答