Object轉byte[];byte[]轉Object

對象轉數組,數組轉對象   

序列化一個對象,反序列化一個對象就是如此  java

 

Java代碼
 
複製代碼
package com.digican.utils;   

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.digican.javabean.TestBean;

public class ObjectAndByte {

/**
* 對象轉數組
* @param obj
* @return
*/
public byte[] toByteArray (Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray ();
oos.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
}

/**
* 數組轉對象
* @param bytes
* @return
*/
public Object toObject (byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}

public static void main(String[] args) {
TestBean tb = new TestBean();
tb.setName("daqing");
tb.setValue("1234567890");

ObjectAndByte oa = new ObjectAndByte();
byte[] b = oa.toByteArray(tb);
System.out.println(new String(b));

System.out.println("=======================================");

TestBean teb = (TestBean) oa.toObject(b);
System.out.println(teb.getName());
System.out.println(teb.getValue());
}

}
複製代碼
複製代碼
package com.digican.javabean;   

import java.io.Serializable;

public class TestBean implements Serializable{

private String name;

private String value;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

}
複製代碼
相關文章
相關標籤/搜索