IO_对象处理流_序列化反序列化_关闭流jdk1.7try-with-resourceJAVA159-160

来源:http://www.bjsxt.com/
一、S02E159_01IO_其他流_对象处理流、序列化、反序列化
引用类型(对象) 保留数据+类型
——反序列化(从文件或字节数组中取出对象) 输入流:ObjectInputStream readObject()
——序列化(把对象保存到文件或字节数组中) 输出流:ObjectOutputStream writeObject()
——注意:
————1)先序列化后反序列化;反序列化顺序必须与序列化一致
————2)不是所有对象都可以序列化,类必须实现java.io.Serializable;不是所有对象的属性都需要序列化,不需要的添加关键字transient

package com.test.io.others;

import java.io.Serializable;
/**
 * 员工类
 * Serializable是空接口,空接口只是标识,此处标识告诉JVM可序列化
 */
public class Employee implements Serializable {
    private transient String name;//不需要序列化,加关键字transient
    private double salary;
    public Employee() {
    }
    public Employee(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
}
package com.test.io.others;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.Arrays;
/**
 * 不是所有对象都可以序列化,类必须实现java.io.Serializable,否则java.io.NotSerializableException
 * 不是所有对象的属性都需要序列化,不需要的添加关键字transient
 */
public class ObjectStream {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        seri("G:/java/test/seri.txt");
        read("G:/java/test/seri.txt");
    }
    /**
     * 序列化
     * @throws IOException 
     * @throws FileNotFoundException 
     */
    public static void seri(String desPath) throws FileNotFoundException, IOException{
        Employee emp = new Employee("张三",100000);
        int[] arr = {1,2,3,4,5};
        //创建源
        File des = new File(desPath);
        //选择流ObjectOutputStream
        ObjectOutputStream oos = new ObjectOutputStream(
                    new BufferedOutputStream(new FileOutputStream(des))
                );
        //操作    写出的顺序与读取的顺序必须一致 为读取准备
        oos.writeObject(emp);
        oos.writeObject(arr);
        //释放资源
        oos.close();
    }
    /**
     * 反序列化
     * @throws IOException 
     * @throws FileNotFoundException 
     * @throws ClassNotFoundException 
     */
    public static void read(String srcPath) throws FileNotFoundException, IOException, ClassNotFoundException{
        //创建源
        File src = new File(srcPath);
        //选择流
        ObjectInputStream ois = new ObjectInputStream(
                    new BufferedInputStream(new FileInputStream(src))
                );
        //操作    读取的顺序与写出一致且必须存在才能读取
        //顺序不一致,数据存在问题
        Object obj = ois.readObject();
        if(obj instanceof Employee){
            Employee emp = (Employee)obj;
            System.out.println(emp.getName());//没有序列化的属性,内容:null
            System.out.println(emp.getSalary());//内容:100000.0
        }
        obj = ois.readObject();
        int[] arr = (int[])obj;
        System.out.println(Arrays.toString(arr));//内容:[1, 2, 3, 4, 5]
        //释放资源
        ois.close();
    }
}

二、S02E160_01IO_关闭流方法_jdk1.7try-with-resource
编写工具类,实现关闭功能

package com.test.io.others;

import java.io.Closeable;
import java.io.IOException;

public class CloseStreamUtil {
    /**
     * 工具类关闭流
     * 可变参数(数量可变):...   只能放到形参最后一个位置,处理方式与数组一致
     * @throws IOException 
     */
    public static void close(Closeable ... io) throws IOException{
        for(Closeable temp : io){
            if(null != temp){
                temp.close();
            }
        }
    }
    /**
     * 使用泛型方法
     * @throws IOException 
     */
    public static <T extends Closeable> void closeAll(T ... io) throws IOException{
        for (T temp : io) {
            if(null != temp){
                temp.close();
            }
        }
    }
}

使用:CloseStreamUtil.close(is,os);或者CloseStreamUtil.closeAll(is,os);
jdk1.7新特性:try-with-resource写法,用来代替之前的try-catch-finally语句块,实现对某些开销大的resource省去写finally语句块释放资源的代码。例如关闭流、断开数据库连接等等,都不再写finally语句块释放资源,try-with-resources会自动释放try后面()内占用的资源
例如:

try(OutputStream os = new FileOutputStream(des,true)) {
    String str = "anything is good \r\n";
    byte[] data = str.getBytes();
    os.write(data,0,data.length);
    os.flush();//强制刷新出去
} catch (IOException e) {
    e.printStackTrace();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值