如何使用Scanner将文件读入字符串数组?该文件具有指定的行数,例如100。此处有大量示例使用arrayList
和BufferedReader
但不是扫描程序或已经修复的数组。
public String[] array;
Scanner inputStream = null;
public String line;
public practice(String theFile) {
array = new String[100];
try {
inputStream = new Scanner(new FileInputStream(theFile));
while (inputStream.hasNextLine()) {
for (int i = 0; i < array.length; i++){
//dont know what to put here
}
}
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
inputStream.close();
}
答案 0 :(得分:2)
你不需要检查是否有下一行,因为你有一个固定的长度和一个try catch来处理它。只需使用for循环但不使用while循环。从那里,它只是所有扫描仪的东西:
for (int i = 0; i < array.length; i++)
{
array[i] = inputStream.nextLine();
}
答案 1 :(得分:1)
int i = 0;
while (inputStream.hasNextLine() && i < array.length())
{
array[i] = inputStream.nextLine();
i++;
}