JAVA 元件(Serializable) 讀取/寫入 檔案中
JAVA 元件(Serializable) 讀取/寫入 檔案中
//元件
import java.io.*;
public class Employee implements Serializable {
private String name;
private String ID;
private float salary;
Employee(String name, String ID, float salary){
this.name = name;
this.ID = ID;
this.salary = salary;
}
public String getName(){
return name;
}
public String getID(){
return ID;
}
public float getSalary(){
return salary;
}
}
//寫入
import java.io.*;
public class WriteData {
public static void main(String[] args){
Employee[] s = new Employee[2];
s[0] = new Employee(“Alex”, “001”, 32000.f);
System.out.println(s[0].getName());
System.out.println(s[0].getID());
System.out.println(s[0].getSalary());
s[1] = new Employee(“Ivy”, “002”, 43000.f);
System.out.println(s[1].getName());
System.out.println(s[1].getID());
System.out.println(s[1].getSalary());
try{
FileOutputStream fs = new FileOutputStream(“Employee.txt”);
ObjectOutputStream out = new ObjectOutputStream(fs);
out.writeObject(s);
out.close();
fs.close();
} catch (IOException e){
System.out.println(e.toString());
}
}
}
//讀取
import java.io.*;
public class ReadData {
public static void main(String[] args){
try{
FileInputStream fs = new FileInputStream(“Employee.txt”);
ObjectInputStream in = new ObjectInputStream(fs);
Employee[] s = (Employee[]) in.readObject();
for(int i=0; i<s.length; i++)
{
System.out.println(s[i].getID());
System.out.println(s[i].getSalary());
}
in.close();
fs.close();
} catch (Exception e){
System.out.println(e.toString());
}
}
}