Re: help on converting bytearrayinputstream to objectinputstream [小糊涂的灵感]

Re: help on converting bytearrayinputstream to objectinputstream
Author: lightblue_daisy
In Reply To: help on converting bytearrayinputstream to objectinputstream
Jun 7, 2004 1:18 PM  
Reply 5 of 5
You have to writeObject first.

A sample code as below, hope it's helpful.
----------------------------------------
                        
try {
//Using ByteArrayInputStream to simulate YOUR socket.getInputStream()
String strSocketInput = "TAIWAN";
ByteArrayInputStream baIn = new ByteArrayInputStream(strSocketInput.getBytes());
DataInputStream oInputStream = new DataInputStream(baIn);

byte[] arr = new byte[oInputStream.available()];
oInputStream.read(arr);
baIn.close();
oInputStream.close();

//A new byte array
String strIdentifier = ", a beautiful country.";
byte[] identifier = strIdentifier.getBytes();

//the final one we will send
byte[] ob = new byte[arr.length + identifier.length];
ByteArrayInputStream baNew = new ByteArrayInputStream(arr);
baNew.read(ob, 0, arr.length);
//Append new byte array
baNew = new ByteArrayInputStream(identifier);
baNew.read(ob, arr.length, identifier.length);

//== Coz we will invoke 'readObject', we have to 'writeObject' first.
ByteArrayOutputStream baOut = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(baOut);
//write the object 'ob' to 'baOut'
objOut.writeObject(ob);
objOut.flush();
objOut.close();

//get the byte array of 'baOut'
byte[] baSend = baOut.toByteArray();
baOut.close();

//retrieve the object 'ob'
ByteArrayInputStream baRecIn = new ByteArrayInputStream(baSend);
ObjectInputStream objIn = new ObjectInputStream(baRecIn);
//the object type of 'ob' is byte[]
byte[] baRec = (byte[])objIn.readObject();

//see what we receive
String strReceive = new String(baRec);
System.out.println("WHAT WE RECEIVED: " + strReceive);
} catch (Exception e) {
e.printStackTrace();
}
Never giveup. Thanks the world.
原文地址:https://www.cnblogs.com/cnsoft/p/58003.html