Java04 save and read the .txt

来源:互联网 发布:als算法 与svd 编辑:程序博客网 时间:2024/04/30 10:15

Now there have a class named Person:

public class Person {

public static int lastId = 0;

private String name;

private Date dateOfBirth;

private String address;

public Person(String name, Date dateOfBirth, String address) {

super();//Now I dont what its.When I search it, I only know that super is the same as parentclass.Using super() means that subclass can invoke all the parentclasss methods.

this.name = name;

this.dateOfBirth = dateOfBirth;

this.address = address;

lastId++;

this.idNumber = lastId;

}

public String toString() {

return "Person [name=" + name + ", dateOfBirth=" + dateOfBirth

+ ", address=" + address + ", idNumber=" + idNumber + ",phoneNum="+phoneNum+"]";

}

public String flatten() {

return name + "," + dateOfBirth.getTime() + "," + address + "," +phoneNum+","+ idNumber;

}

}

Store the Person’s message:

public static void storeObjects(Person[] arr) {

File file = new File("PersonFile.txt");

try {

BufferedWriter fw = new BufferedWriter(new FileWriter(file, true));

for (int i = 0; i < arr.length; i++) {

fw.write(arr[i].flatten());//To invoke Person. flatten() to stroe message by some rules.

fw.newLine();

}

fw.flush();

fw.close();

} catch (IOException e) {

}

}

Read the .txt’s messages

public static boolean readObjects(Person[] arr) {

 File file = new File("PersonFile.txt");

 String line;

 Person x;

 String name;

 Date dob;

 String address;

 int id;

 int position = 0;

 try {

 BufferedReader fr = new BufferedReader(new FileReader(file));

 while ((line = fr.readLine()) != null) {

 String[] s = line.split(",");

// The message we stroe are liking that:

//We using a (String line) to receive one line message,then invode line. split(",") to get a String[].

 name = s[0];

 dob = new Date(Long.parseLong(s[1]));

 address = s[2];

 id = Integer.parseInt(s[3]);

 x = new Person(name, dob, address);

 arr[position] = x;

 position++;

 }

 fr.close();

 } catch (IOException e) {

 return false;

 }

 return true;

 }

原创粉丝点击