transient:该数据不需要序列化,数据透明(输出显示null),private transient String name;
创新互联主营曾都网站建设的网络公司,主营网站建设方案,成都app软件开发公司,曾都h5小程序制作搭建,曾都网站营销推广欢迎曾都等地区企业咨询
//写出后读取,读取的数徐与写出保持一致
public class n {
public static void main(String[]args) throws IOException, ClassNotFoundException
{
写入字节数组
//写出 序列化
ByteArrayOutputStream os=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(os));
ha ff=new ha("hh",222);
oos.writeUTF("哈哈");
oos.writeChar('q');
oos.writeBoolean(false);
oos.writeObject(ff);
oos.flush();
byte[] datas=os.toByteArray();
oos.close();
//读取 反序列化
ObjectInputStream ois =new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
String s=ois.readUTF();
char ch=ois.readChar();
boolean flag=ois.readBoolean();
Object str=ois.readObject(); //Object需要强制转换
//还原(判断是哪个类,然后强制转换):
if (str instanceof String ) //是String类就直接转换成字符串
{
String s1=(String)str;
System.out.println(s1);
}
if(str instanceof Data)
{
Date d=(Date)str;
System.out.println(d);
}
if(str instanceof ha)
{
ha fr=(ha)str;
System.out.println(fr.getName()+fr.getSalary());
}
ois.close();
}
//javabean,用于封装数据
class ha implements java.io.Serializable {
private transient String name; //该数据不需要序列化,数据透明
private double salary;
public ha()
{
}
public ha(String name,double salary)
{
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;
}
}
写入文件:
ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("D:/d/s")));
ha ff=new ha("hh",222);
oos.writeUTF("what");
oos.writeObject(ff);
oos.flush();
oos.close();
//使用时,反序列化对象
ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream("D:/d/s")));
String s=ois.readUTF();
Object it=ois.readObject();
if(it instanceof ha)
{
ha q=(ha)it;
System.out.println(q.getName()+q.getSalary());
}
ois.close();
//javabean 用于封装数据
class ha implements java.io.Serializable {
private transient String name; //该数据不需要序列化,数据透明
private double salary;
public ha()
{
}
public ha(String name,double salary)
{
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;
}
}
文章名称:java_io_对象流,能够保存基本数据类型和对象
链接URL:https://www.cdcxhl.com/article40/ijccho.html
成都网站建设公司_创新互联,为您提供微信小程序、定制网站、响应式网站、自适应网站、服务器托管、虚拟主机
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联