Pages

Monday, January 10, 2011

Write object to the file in java

When you write a code and it's need to save data result from the code, then you'll need to write it to file. In java, writing the object to file are very easy.. Below are the example in writing it. But first, make a class which implement serializable

object1.java


package utility;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class object1 implements serializable {
private String attrib1;
private String attrib2;
private String attrib3;
private String attrib4;

public object1(){
}

//create setter and getter
}


after that, then set the value for each attribut in object 1, then call the method in this export class

export.java


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package utility;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Fahmi_rnf
*/
public class exportData implements Serializable{
public exportData(){

}

public exportData(Object exp,String fileName) throws IOException{
FileOutputStream f;
try {
f = new FileOutputStream(fileName);
ObjectOutputStream s = new ObjectOutputStream(f);

s.writeObject(exp);
s.flush();
} catch (FileNotFoundException ex) {
Logger.getLogger(exportData.class.getName()).log(Level.SEVERE, null, ex);
}



}
}

0 comments:

Post a Comment

 

Sample text

Sample Text