我不能相信我必须要求这样一个简单的问题,但似乎我找不到解决方案。我在一个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,因此它必须是不使用该导入的东西。再次感谢。
的一个字符串数组“没'工作'*你的代码不工作?我们无法读懂你的想法。 – awksp
假设你的文件路径是正确的,用'hasNextLine()'''nextLine()'方法试试'Scanner'对象。 –
问题是打开文件或读取行?抛出了'IOException'吗? 这可能会有所帮助,顺便说一句:http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java –