java将类写入二进制文件(系列化类)

实现代码

  • 通过ObjectOutputStream类的writeObject函数可以直接向二进制文件中写入类对象
  • 这种方式得到的二进制文件会比文本文件更大,可能是二进制文件中含有类对象的其他信息
  • 类对象需要实现Serializable接口,接口中没有需要实现的函数

测试的类

class TestDataStruct implements Serializable{
    String name;

    public TestDataStruct(String name,double x,double y,double z,String atr1,String atr2){
        this.name = name;
        this.x = x;
        this.y = y;
        this.z = z;
        this.atr1 = atr1;
        this.atr2 = atr2;
    }
}

文本文件

F1,8251.409,8252.466,38.477,val1,vall1
F2,8252.129,8251.382,38.46,val2,vall2
F3,8254.335,8250.181,38.443,val3,vall3
F4,8256.815,8249.749,38.433,val4,vall4
F5,8253.534,8253.266,38.395,val5,vall5
F6,8253.058,8255.03,38.157,val6,vall6
F7,8255.883,8251.085,38.401,val7,vall7
F8,8252.952,8252.742,38.403,val8,vall8
F9,8250.394,8255.645,38.461,val9,vall9

写入代码与读取代码

/**写入二进制文件
*从文本文件中读入数据,写入到二进制文件中
*/
    static void readClass2File() throws IOException {
        //序列化类以二进制传入文件
        ObjectOutputStream objectOutputStream= new ObjectOutputStream(
                new FileOutputStream(new File("/home/fly/桌面/hadoopPrj/tempBinary")));

        Scanner in = new Scanner(new File("/home/fly/桌面/hadoopPrj/data/testData.csv"));
        String str;
        String strs[];
        TestDataStruct testDataStruct;

        while (in.hasNextLine()) {
            str = in.nextLine();
            strs = str.split(",");
            testDataStruct = new TestDataStruct(strs[0], Double.valueOf(strs[1]),
                    Double.valueOf(strs[2]),Double.valueOf(strs[3]),strs[4],strs[5]);
            objectOutputStream.writeObject(testDataStruct);

/*
*读取上一个函数写入的文件
*/
    static void readFile2Class() throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("/home/fly/桌面/hadoopPrj/tempBinary")));
        TestDataStruct testDataStruct;
        testDataStruct = (TestDataStruct)objectInputStream.readObject();

        try {
            while (testDataStruct != null) {    //通过EOFException来判断是否读到文件尾,判断作用不大
                System.out.println(testDataStruct.name);
                System.out.println(testDataStruct.z);
                testDataStruct = (TestDataStruct) objectInputStream.readObject();
            }
        } catch (EOFException e) {
            //        e.printStackTrace();
        } finally {
            objectInputStream.close();
        }
    }

        }
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值