我有一个包含以下格式数据的文本文件
Vehicle:Bike
MOdel:FZ
Make:
Yamaha
Description
abcdefgh
ijklmn
problems
gear problem, fork bend.
this is auto data
***********************************end***********************
Vehicle:Bike
MOdel:R15
Make:
Yamaha
Description
1234,
567.
890
problems
gear problem, fork bend.
oil leakage
this is auto data
***********************************end***********************
我已经给出了2个数据但是在文本文件中还有更多这样的数据我想要读取它并将其存储在散列图中,以便
Bike:FZ:Yamaha:abcdefghijklmn:gear problem,fork bend.
Bike:R15:Yamaha:1234,567.890:gear problem,fork bend.oil leakage
我的示例代码:
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String sCurrentLine;
int i = 0;
int j = 0;
hmap = new HashMap<String, Integer>();
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
sCurrentLine = sCurrentLine.trim();
if (!sCurrentLine.equals("")) // don't write out blank lines
{
if (sCurrentLine.startsWith("***********")) {
i++;
} else {
if (sCurrentLine.startsWith("Vehicle:")) {
String[] veh = sCurrentLine.split(":");
String vehicle = tType[1];
}
if (sCurrentLine.startsWith("Model:")) {
String[] mod = sCurrentLine.split(":");
String model = iShield[1];
}
hmap.put(0,i+":"+vehicle+":"+model);
}
}
j++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
不确定如何阅读---&gt;制作,描述&amp;问题属性。
答案 0 :(得分:0)
您需要ObjectInputStream
。
一个例子:
/* Create an ObjectInputStream for your text file
* and a hash map to store the values in. */
ObjectInputStream obj = new ObjectInputStream(new FileInputStream(textFile));
hmap = (HashMap<String, String>) obj.readObject(); // I assume you want strings.
hmap.put("value", var); // Var can be whatever other strings you created.
// It is always a good idea to close streams.
obj.close();
请记住,如果您需要将另一个变量类型放入哈希映射中,则可以使用HashMap<String, byte[]>
之类的内容创建它。
显然,您需要实施已经创建的方法来确定每个变量。
如果我不够具体,或者遗漏了重要的事情,请告诉我。