如何从文本文件中选择一行并将其转换为数组对象?

时间:2012-02-01 04:41:08

标签: java arrays line text-files

好的,这是代码,我需要以某种方式从文本文件中取一行并转换为数组对象。比如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);
    }
}

2 个答案:

答案 0 :(得分: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)
}

注意:您的代码可以更清晰,您可以在最后处理关闭资源

答案 1 :(得分: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 []);