c#可以这样写,java中怎么写???//【客户端】
//这是你的object数组
Object[] objArray = new Object[10];
//内存流(需要引用 System.IO)
MemoryStream ms=new MemoryStream();
//序列化(需要引用 System.Runtime.Serialization.Formatters.Binary)
BinaryFormatter bf = new BinaryFormatter();
//将数据保存到内存流
bf.Serialize(ms, objArray);//【服务端】
MemoryStream msGet;//你通过自己的方法获取到内存流
BinaryFormatter bfServer = new BinaryFormatter();
//反序列化,得到数据
Object[] getObjectArray = (Object[])bf.Deserialize(msGet); c#可以这样写,java中怎么写???
//这是你的object数组
Object[] objArray = new Object[10];
//内存流(需要引用 System.IO)
MemoryStream ms=new MemoryStream();
//序列化(需要引用 System.Runtime.Serialization.Formatters.Binary)
BinaryFormatter bf = new BinaryFormatter();
//将数据保存到内存流
bf.Serialize(ms, objArray);//【服务端】
MemoryStream msGet;//你通过自己的方法获取到内存流
BinaryFormatter bfServer = new BinaryFormatter();
//反序列化,得到数据
Object[] getObjectArray = (Object[])bf.Deserialize(msGet); c#可以这样写,java中怎么写???
总之没有c#中那么方便,c#中5行代码能搞定可能java中需要10行
我是想把object数组变成字节数组,然后用socket传送字节数组
ObjectOutputStream oos = null;
OutputStream os = null;
try {
os = new FileOutputStream("c:\\xxxx"); // 输出流你可以随便定义了
oos = new ObjectOutputStream(os);
oos.writeObject(objArray);
} catch (Exception e) {
throw e;
} finally {
IOUtils.closeQuietly(oos);
IOUtils.closeQuietly(os);
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;public class Test2 { public static void main(String[] args) throws IOException {
Serializable obj = "abc";
byte[] array = toByteArray(obj);
System.out.println("Array: "+Arrays.toString(array));
obj = toObject(array);
System.out.println(obj);
} /**byte[]转对象*/
public static Serializable toObject(byte[] bytes) throws IOException {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
Serializable ser = null;
try {
ser = (Serializable) in.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ser;
} /**对象转byte[]*/
public static byte[] toByteArray(Serializable object) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(buf);
o.writeObject(object);
byte[] bytes = buf.toByteArray();
return bytes;
}
}
两个方法,顺带一个小例子。
注:java中要变成byte[]需要实现Serializable接口才行。
/// string集合转成byte[]数组
/// </summary>
/// <returns>序列化后的字节数组</returns>
private byte[] SerializeOnlineList()
{
StringCollection onlineList = new StringCollection();
onlineList.Add("张三");
onlineList.Add("李四");
IFormatter format = new BinaryFormatter();
MemoryStream stream = new MemoryStream();//创建其支持存储区为内存的流
format.Serialize(stream, onlineList);
byte[] ret = stream.ToArray();
stream.Close();
return ret;
}
因为socket传送的时候只能传byte[],所以要把object[]转成byte[],才能发送.
C# -- 需要敲两下键盘
java -- 需要四下
遵循引用的逻辑:
C# 确实比java简单一半.有聊啊!
把 ObjectOutputStream再封装成一个 ByteArrayOutputStream就可以了