将String文本文件转换为对象数组

时间:2012-02-01 03:39:23

标签: java arrays string text-files

我想使用文本文件并将每一行放入一个classobject数组中。这是我的代码

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());
}

我需要将其转换为数组对象,这就是我希望它看起来像

的方式
Patient1 p[] = new Patient1[5];
p[0] = 001, "John", 17, 100, 65, 110, 110, 110, 109, 111, 114, 113, "Swaying, Nausea";
p[1] = 002, "Sun Min", 18, 101, 70, 113, 113, 110, 119, 111, 114, 113, "None";

等等。

2 个答案:

答案 0 :(得分:1)

建立AVD的建议,你可以用一个接受你的值的构造函数来完成你想要的东西 - 尽管不建议在构造函数中使用太多的参数(为了可读性和调试的缘故)。根据您的数据订购和阅读方式,您甚至可以使用String.split将所有内容整合为一种类型(即字符串)。

public class Patient {

   public Patient(String name, String id, String symptoms, String measurements) {  to get the individual fields from using a delimiter.

        // Stuff to fill in the fields goes here
    }
}

您可以使用new Patient("John, "001", "Swaying, Nausea", ...)来调用此方法。同样,这取决于您如何读取数据;如果您无法以合理的方式提取数据,那么您也可以选择创建accessors and mutators

答案 1 :(得分:0)

您必须使用13个字段,构造函数和setter / getter创建Patient类。

public class Patient
{
   private String field1;
   private String field2; 
   private int field3;
   ....
   public void setField1(String field1) { this.field1=field1; }
   public String getField1() { return field1;}
   ...   
}

并使用ArrayList<Patient>代替数组。

ArrayList<Patient> patients=new ArrayList<Patient>();
Patient pat=new Patient();
//set value to the patient object
patients.add(pat);
相关问题