2014-07-06 108 views
0

我不能相信我必須要求這樣一個簡單的問題,但似乎我找不到解決方案。我在一個txt文件中有10個名字,我想用這個名字創建一個String數組。這些名稱每行的名稱爲1,因此共有10行。我已經試過這個代碼從txt列表到字符串數組

String[] txtToString() throws IOException { 

    Scanner s = null; 
    String[] string = new String[10]; 
    int count = 0; 

    try { 
     s = new Scanner(new BufferedReader(new FileReader(
       "file:///android_res/raw/words.txt"))); 

     while (s.hasNext()) { 
      count++; 
      string[count] = s.next(); 
     } 
    } finally { 
     if (s != null) { 
      s.close(); 
     } 
    } 
    return string; 
} 

但它沒有奏效。我試過也只是把「words.txt」作爲文件路徑,但仍然沒有。謝謝您的幫助。 P.s.由於某些未知原因,我無法導入java.nio.file.Files,因此它必須是不使用該導入的東西。再次感謝。

+1

的一個字符串數組「沒'工作'*你的代碼不工作?我們無法讀懂你的想法。 – awksp

+0

假設你的文件路徑是正確的,用'hasNextLine()'''nextLine()'方法試試'Scanner'對象。 –

+0

問題是打開文件或讀取行?拋出了'IOException'嗎? 這可能會有所幫助,順便說一句:http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java –

回答

0

確定我解決利用該方法:

String[] txtToString() { 
    String[] string = new String[10]; 
    int count = 0; 
    try { 
     Resources res = getResources(); 
     InputStream in = res.openRawResource(R.raw.words); 

     BufferedReader reader = new BufferedReader(
       new InputStreamReader(in)); 

     String line; 

     while ((line = reader.readLine()) != null) { 
      string[count] = line; 
      count++; 
     } 

    } catch (Exception e) { 
     // e.printStackTrace(); 

    } 
    return string; 
} 

返回exaclty從txt文件 「words.txt」 10個元素

1

嘗試交換這兩行:

count++; 
string[count] = s.next(); 

在您的計數變量是從1將10的那一刻,而不是0到9喜歡你想讓它。

+0

是的表示感謝,我糾正它,因爲它顯然是錯誤的,但我仍然無法使代碼工作 – Ardi

0

嘗試這種

while (s.hasNext()) { 
    string[count++] = s.next(); 
} 
相關問題