Java对象流实例代码

时间:2022-11-22 10:24:45

将日期对象和向量对象写入文件,然后从文件中读出并输出到屏幕上

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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对象流实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/sac761/article/details/47038609