2012-02-01 27 views
2

好吧,這是代碼,我需要以某種方式從文本文件中取出一行並轉換爲數組對象。像P [0] = 「asdasdasd」如何從文本文件中選取一行並將其轉換爲數組對象?

public class Patient2 { 
    public static void main(String args[]) 
    { 

     int field = 0; 
     String repeat = "n"; 
     String repeat1 = "y"; 
     Scanner keyIn = new Scanner(System.in); 



     // FILE I/O 
     try{ 
       // Open the file that is the first 
       // command line parameter 
       FileInputStream fstream = new FileInputStream("Patient.txt"); 
       BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
       String strLine; 
       //Read File Line By Line 
       while ((strLine = br.readLine()) != null) { 
       // Print the content on the console 
       System.out.println (strLine); 
       } 
       //Close the input stream 
       in.close(); 
       }catch (Exception e){//Catch exception if any 
       System.err.println("Error: " + e.getMessage()); 
       } 
     ArrayList<Patient1> patients=new ArrayList<Patient1>(); 
     Patient1 p =new Patient1(); 
     //set value to the patient object 
     patients.add(p); 
     System.out.println(p); 
    } 
} 
+0

對於想要轉換爲數組的行的模式以及要設置它的位置,您可以更具體一些嗎? – 2012-02-01 04:51:03

回答

2

在打印到控制檯,您可以將其添加到List<String>

List<String> lines = new ArrayList<String>(); 
while ((strLine = br.readLine()) != null) { 
    // Print the content on the console 
    System.out.println (strLine); 
    lines.add(strLine) 
} 

注相反:你的代碼可以是乾淨多了,你可以處理閉幕資源在最後

+0

好吧我需要將字符串轉換爲數組,如p [0] =「」; – user1181810 2012-02-01 04:49:18

+1

你永遠不知道文本文件的長度是多少,所以最好使用List,然後你可以將這個列表轉換爲數組 – 2012-02-01 04:55:03

2

只需使用ArrayList<String>add(strline);
和使用toArray(new String [])獲取輸入流已關閉後的數組。

ArrayList<String> list = new ArrayList<String>(); 
... 

while ((strLine = br.readLine()) != null) { 
    list.add(strLine); 
} 
... 

String [] s = list.toArray(new String []); 
+0

列表是不是初始化的 – user1181810 2012-02-01 05:05:13

+0

那麼初始化它呢? :p確保它是一個數據字段/類變量。 – rtheunissen 2012-02-01 05:07:03

+0

把'ArrayList list = new ArrayList ();'在你的類聲明和你的'main'方法之間。 – rtheunissen 2012-02-01 05:08:27

相關問題