有不同的方法可以解决这个问题,这不是安卓问题。以下代码可能会有用(将文本文件放入 res\raw 文件夹,例如 res\raw\test.txt):
(您可以在LINK 中尝试类似的代码)
final String PHONE = "PHONE";
final String ADDRESS = "ADDRESS";
final String NAME = "NAME";
InputStream in_s = getResources().openRawResource(R.raw.test);
byte[] b = "".getBytes();
try {
b = new byte[in_s.available()];
in_s.read(b);
} catch (IOException ex) {
System.out.println("Error!");
}
String[] words = (new String(b)).replace(":: label_", "").split("\\n");
HashMap<Integer, HashMap<String, String>> h1 = new HashMap<Integer, HashMap<String, String>>();
int groupNumber = 1;
for (int i = 0; i < words.length; i++) {
String str = words[i];
if (!str.isEmpty()) {
if (str.equals(String.valueOf(groupNumber))) {
HashMap<String, String> h2 = new HashMap<String, String>();
h1.put(groupNumber, h2);
} else {
h1.get(groupNumber).put(PHONE, words[i]);
h1.get(groupNumber).put(ADDRESS, words[++i]);
h1.get(groupNumber).put(NAME, words[++i]);
groupNumber++;
}
}
}
System.out.println(h1);
这段代码显示了一个哈希图:
{1={NAME=<PHONE_1>, ADDRESS=[ADDRESS_1], PHONE=[NAME_1]}, 3={NAME=<PHONE_3>, ADDRESS=[ADDRESS_3], PHONE=[NAME_3]}, 2={NAME=<PHONE_2>, ADDRESS=[ADDRESS_2], PHONE=[NAME_2]}}
您可以通过以下方式获取值:
h1.get(1).get(PHONE);//this returns de phone value from group 1
此代码仅适用于您的文本文件(但您可以更改其他结构):
:: label_1
[NAME_1]
[ADDRESS_1]
<PHONE_1>
:: label_2
[NAME_2]
[ADDRESS_2]
<PHONE_2>
:: label_3
[NAME_3]
[ADDRESS_3]
<PHONE_3>
(已编辑)
假设文字是http://pastebin.com/fPDm72fe,我改了一段代码:
String[] words = (new String(b)).split("\\n");
HashMap<Integer, HashMap<String, String>> h1 = new HashMap<Integer, HashMap<String, String>>();
int groupNumber = 1;
for (int i = 0; i < words.length; i++) {
String str = words[i];
if (!str.trim().isEmpty()) {
if(str.contains("::")){
HashMap<String, String> h2 = new HashMap<String, String>();
h1.put(groupNumber, h2);
} else {
h1.get(groupNumber).put(PHONE, words[i]);
h1.get(groupNumber).put(ADDRESS, words[++i]);
h1.get(groupNumber).put(NAME, words[++i]);
groupNumber++;
}
}
}
你可以试试他的here