我正在构建一个获取国家/地区名称并返回其国家/地区代码(iso/电话前缀)的函数。我向我的项目(应用程序的根目录)添加了一个文本文件,其中包含国家/地区的键值对及其国家/地区代码,格式如下:
"Abkhazia":7840,
"Abkhazia":7940,
"Afghanistan":93,
"Albania":355,
"Algeria":213,
用户在 EditText
框中输入国家/地区名称,该函数应返回代码。
editTextCountryInput = (EditText) findViewById(R.id.editTextCountryInput);
getCountryCode(editTextCountryInput.getText().toString());
功能:
private int getCountryCode(String countryName){
try{
BufferedReader reader = new BufferedReader(new FileReader(new File("countries.txt")));
String inputLine = null;
LinkedHashMap<String,String> dictionary = new LinkedHashMap<String,String>();
try{
while((inputLine = reader.readLine()) !=null){
String[] words = inputLine.split(":"); //split each line by : delimiter
for(String word: words){
Log.i("splitting ", " line");
dictionary.put(word,?); //what should be the second arg?
}
}
}catch (IOException e){
e.printStackTrace();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
int countryCode =(int) dictionary.get(countryName);
return countryCode;
}
我想读取文本文件的每一行,分割分隔符为(“:”)的每一行,并将每个分割的键值对放入 LinkedHashMap
中。 2个问题:
1. 我收到错误 java.io.FileNotFoundException:country.txt: open failed: ENOENT (No such file or directory)
。当我测试文件的绝对路径
时,我得到了“/countries.txt” - 但它仍然因该错误而失败。
2. 使用String.split(":")
方法分割读取行后,我不知道如何以键值方式将这两部分存储在hashMap中。
这是我用来确定绝对路径的代码:
File f = new File("countries2.txt");
Log.i("abs path: ", f.getAbsolutePath());
编辑:
我在 Android Studio 中创建了一个新的 assets
文件夹(右键单击应用程序 -> 新的 Assets 文件夹 -> 完成)并放置了我的 countries.txt
文件,但我仍然收到 FileNotFound 异常。
最佳答案
- 那是因为FileReader找不到您的 txt 文件。
你可以尝试:
String[] words = inputLine.split(":"); //split each line by : delimiter dictionary.put(words[0],words[1]); //what should be the second arg?
words[0]
将保存名称,而 words[1]
将保存数字。
关于java - Android - 从文件中读取文本并将其添加到 LinkedHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989495/