Write date objects and vector objects to a file, then read from the file and output to the screen
package objstream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.Date;import java.util.Vector;import java.util.logging.Level;import java.util.logging.Logger;import javafx.scene.chart.PieChart.Data;/** * * @author Administrator */public class ObjStream {/** * @param args the command line arguments */public static void main(String[] args) throws IOException {try {// These 2 sentences are in line with FileOutputStream fout = new FileOutputStream("test.txt"); //is equivalent FileOutputStream fout = null;File f = new File("test.txt");Vector v = new Vector();//Vector variable v.add("No reward for success");v.add("Excellent talent");v.add("Everything");fout = new FileOutputStream(f);ObjectOutputStream Obj = new ObjectOutputStream(fout);Object Oj = new Object();Oj = new Date();ObjectObject(Oj);Object.writeObject(v);Object.close();FileInputStream Fin = new FileInputStream(f);ObjectInputStream Ois = new ObjectInputStream(Fin);Object Oji = new Object();//Why do you need to use 2 OBJECTs to output and ask for advice here? Oji = Ois.readObject();//If you don't use 2 OBJECTs, you will only output the time System.out.println(Oji);Object Oji2 = new Object();Oji2 = Ois.readObject();System.out.println(Oji2);}catch (FileNotFoundException ex) {Logger.getLogger(ObjStream.class.getName()).log(Level.SEVERE, null, ex);}catch (ClassNotFoundException ex) {Logger.getLogger(ObjStream.class.getName()).log(Level.SEVERE, null, ex);}}}Object input stream) can read the original data and types written using the object output stream, and together with the file input and output stream, the persistent storage of objects can be achieved.
result:
Fri Jul 24 11:28:01 CST 2015
[Not seeking merit, outstanding talent, ever-changing]
Successfully built (total time: 2 seconds)
But the test.txt file is garbled~How to break it?
Summarize
The above is all about the Java object streaming instance code in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!