Skip to content

Instantly share code, notes, and snippets.

Created January 5, 2013 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4461830 to your computer and use it in GitHub Desktop.
Save anonymous/4461830 to your computer and use it in GitHub Desktop.
This is a simple program to test read write Java objects
package me.yogedra.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ReadWriteObjects {
static String dataFile = "/tmp/contactEmployee.dat";
public static void main(String[] args) {
if(args != null && args.length > 0){
dataFile = args[0];
}
ContractEmployee [] list = new ContractEmployee [] {
new ContractEmployee("CE001", "Foo1 Bar3", "India", 15.0f),
new ContractEmployee("CE002", "Foo2 Bar3", "USA", 95.0f),
new ContractEmployee("CE002", "Foo3 Bar3", "Australia", 45.0f),
};
write(list, dataFile);
ContractEmployee [] readList = read(dataFile);
for(ContractEmployee e : readList){
System.out.printf("Id: %1$s\nName: %2$s\nAddress: %3$s\nDaily Rate: %4$4.2f\n", e.empCode, e.empName, e.empAddress, e.empDailyRate);
}
}
private static ContractEmployee[] read( String file){
try{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(file)));
Object o = ois.readObject();
ois.close();
ContractEmployee [] d = (ContractEmployee[]) o;
return d;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
private static void write(ContractEmployee [] data, String file){
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(file)));
oos.writeObject(data);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static class ContractEmployee implements Serializable{
String empCode;
String empName;
String empAddress;
float empDailyRate;
public ContractEmployee(){
}
public ContractEmployee(String empCode, String empName,
String empAddress, float empDailyRate) {
super();
this.empCode = empCode;
this.empName = empName;
this.empAddress = empAddress;
this.empDailyRate = empDailyRate;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment