溶液1
List<String[]> arrays = new ArrayList<String[]>(); //You need an array list of arrays since you dont know how many lines does the text file has
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
String arr[] = str.split(" ");
if(arr.length>0) arrays.add(arr);
}
in.close();
} catch (IOException e) {
}
在端陣列將包含每個數組。在您的例子arrays.length()==4
要遍歷數組了:
for(String[] myarr : arrays){
//Do something with myarr
}
解決方案2:我不認爲這是一個好主意,但如果你是確保文件始終是要包含4條線你可以用空格字符做到這一點
String arr1[];
String arr2[];
String arr3[];
String arr4[];
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
str = in.readLine();
arr1[] = str.split(" ");
str = in.readLine();
arr2[] = str.split(" ");
str = in.readLine();
arr3[] = str.split(" ");
str = in.readLine();
arr4[] = str.split(" ");
in.close();
} catch (IOException e) {
}
謝謝,但我的意思是,每一行都會被保存不同的數組英寸例如我將有4個不同的陣列,每個陣列的大小爲10。不在同一個陣列中。 – Jessy 2010-03-28 18:40:39
例如在txt文件中有4行 會創建4個數組。 每個陣列的大小爲10. 並且陣列上的每個元素可以被稱爲例如。 array1.get(i) – Jessy 2010-03-28 18:42:41
我已經更新了答案以迭代4個數組。 你總是會有4個陣列嗎? – Enrique 2010-03-28 19:00:06