2014-07-06 113 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(); 
} 
相关问题