簡體   English   中英

Android-從文件中讀取文本並將其添加到LinkedHashMap

[英]Android - Read text from file and add it to a LinkedHashMap

我正在構建一個獲取國家名稱並返回其國家代碼(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: countries.txt: open failed: ENOENT (No such file or directory) 當我測試文件的absolute path我得到了“ /countries.txt”-但仍然由於該錯誤而失敗。
2.使用String.split(":")方法拆分讀取行后,我不知道如何以鍵值方式將這兩部分存儲在hashMap中。

這是我用來確定絕對路徑的代碼:

File f = new File("countries2.txt");
        Log.i("abs path: ", f.getAbsolutePath());



編輯:
我創建了一個新的assets Android Studio中的文件夾(在應用程序右鍵- >新資產夾- >完成),並把我的countries.txt文件,但我仍然得到FileNotFound例外。

  1. 這是因為FileReader無法找到您的txt文件。
  2. 您可以嘗試:

     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]將保留數字。

我認為第一個問題很簡單,告訴您找不到文件,第二個問題您可以使用數組,例如

    String[] a ="this iskey:and its value".split(":");
    System.out.println(a[0]);
    System.out.println(a[1]);
    HashMap<String, String> map = new HashMap<String, String>();
    String key =a[0];
    String value =a[1];
    map.put(key, value);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM