很难理解这个问题的含义,但是如果您只想从 .txt 文件中读取行并放入数组中,那么这两种方法可能会有所帮助。
您只需要调用String[] textArray = readFromFile("yourfilename.txt");
This 为您提供一个数组,其中文件中的每一行作为一个元素。
Scanner fScan(String filename) {
Scanner sc = null;
try {
sc = new Scanner(new File(fname));
} catch (FileNotFoundException e) {
System.out.println("File not found:" + fname + " " + e);
}
return sc;
}
String[] readFromFile (String fname) {
Scanner sc = fScan(fname);
int length = 0;
String lineCounter;
while (sc.hasNext()){
lineCounter = sc.nextLine();
length++;
}
String[] array = new String[length];
sc = fScan(fname);
for (int i = 0; i < length; i++) {
array[i] = sc.nextLine();
}
sc.close();
return array;
}