Java对象流实例代码
将日期对象和向量对象写入文件,然后从文件中读出并输出到屏幕上
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 {
//这2句与FileOutputStream fout = new FileOutputStream("test.txt");
//是等价的
FileOutputStream fout = null;
File f = new File("test.txt");
Vector v = new Vector();
//Vector变量
v.add("不求有功");
v.add("才华出众");
v.add("瞬息万变");
fout = new FileOutputStream(f);
ObjectOutputStream Obj = new ObjectOutputStream(fout);
Object Oj = new Object();
Oj = new Date();
Obj.writeObject(Oj);
Obj.writeObject(v);
Obj.close();
FileInputStream Fin = new FileInputStream(f);
ObjectInputStream Ois = new ObjectInputStream(Fin);
Object Oji = new Object();
//这里为什么要用2个OBJECT来输出求指教
Oji = Ois.readObject();
//不用2个的话只输出时间
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);
}
}
}
对象输入流)可读取使用对象输出流写入的原始数据和类型,与文件输入输出流一起可以实现对象的持久性存储。
结果:
Fri Jul 24 11:28:01 CST 2015
[不求有功, 才华出众, 瞬息万变]
成功构建 (总时间: 2 秒)
但是test.txt文件里是乱码~~怎么破??
总结
以上是 Java对象流实例代码 的全部内容, 来源链接: utcz.com/z/324541.html