2010-03-28 106 views
4

如何將文本文件內容保存到不同的陣列?將輸入從文本文件保存到數組

我的文本文件內容是這樣的;

12 14 16 18 13 17 14 18 10 23 
pic1 pic2 pic3 pic4 pic5 pic6 pic7 pic8 pic9 pic10 
left right top left right right top top left right 
100 200 300 400 500 600 700 800 900 1000 

如何將每行保存到不同的數組? 例如

line 1 will be saved in an array1 
line 2 will be saved in an array2 
line 3 will be saved in an array3 
line 4 will be saved in an array4 

回答

3

溶液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) { 
    } 
+0

謝謝,但我的意思是,每一行都會被保存不同的數組英寸例如我將有4個不同的陣列,每個陣列的大小爲10。不在同一個陣列中。 – Jessy 2010-03-28 18:40:39

+0

例如在txt文件中有4行 會創建4個數組。 每個陣列的大小爲10. 並且陣列上的每個元素可以被稱爲例如。 array1.get(i) – Jessy 2010-03-28 18:42:41

+0

我已經更新了答案以迭代4個數組。 你總是會有4個陣列嗎? – Enrique 2010-03-28 19:00:06