2013-05-02 80 views
1

Im相當肯定我只是問一個愚蠢的問題,但是,突出部分說,在有上有讀取文本文件並填充數組中的數據。

UniPub這個數據的txt文件; 112 Binara聖; ACT
MooseHeads; 54科恩聖; ACT
立方; 24莫森聖ACT

生病使用此代碼讀取它在我的應用程序:

package au.edu.canberra.g30813706; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.Arrays; 

import android.app.Activity; 
import android.os.Environment; 


public class FileReader extends Activity{{ 

    ArrayList<String> sInfo = new ArrayList<String>(); 

    String txtName = "AccomodationTxt.txt"; 
    File root = Environment.getExternalStorageDirectory(); 
    File path = new File(root, "CanberraTourism/" + txtName); 

    try { 

     BufferedReader br = new BufferedReader (
          new InputStreamReader(
          new FileInputStream(path))); 
     String line; 
     String[] saLineElements; 
     while ((line = br.readLine()) != null) 
     { 
      //The information is split into segments and stored into the array 
      saLineElements = line.split(";"); 
      for (int i = 0; i < saLineElements.length; i++) 
        sInfo.add(saLineElements[i]); 
      //sInfo.addAll(Arrays.asList(saLineElements[0], saLineElements[1], saLineElements[3]));  
     } 
     br.close(); 


    } 
    catch (FileNotFoundException e) { 

     System.err.println("FileNotFoundException: " + e.getMessage()); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }} 
} 

我將如何區分Array中的線?

例如

我想顯示一個頁面上的名稱的文本,所以只有

UniPub
MooseHeads
立方

+0

您是否總是要以格式「first_val; second_val; third_val」存儲三個值? – 2013-05-02 12:30:25

+0

您的代碼當前是否對字符串輸入進行了任何拆分? – kabuto178 2013-05-02 12:31:39

+0

爲什麼你不把行存儲在一個數組中,當你需要它時,你可以拆分這些行並使用這些信息?這樣你就可以將每行的所有信息分開。或者是否有必要在開始時分裂? – Anila 2013-05-02 12:32:03

回答

1

有關將字符串數組到ArrayList什麼而不是個別元素。
像這樣:

ArrayList<String[]> sInfo = new ArrayList<String[]>(); 
String line; 
String[] saLineElements; 
while ((line = br.readLine()) != null) 
{ 
    //The information is split into segments and stored into the array 
    saLineElements = line.split(";"); 
     sInfo.add(saLineElements); 
} 

然後你可以遍歷sInfo並使用第一個元素sInfo每個陣列英寸

相關問題