In Java network programming, the byte array is important, it can transmit any material (text, audio, video, pictures, etc.), so it is important to master the mutual transformation of byte array and other data types.
Example code:
PackageCom.lky.util;ImportJava.io.ByteArrayInputStream;ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;ImportOrg.apache.commons.logging.Log;Importorg.apache.commons.logging.LogFactory;Importcom.lky.model.Student;/*** @ClassName: objecttobytearray* @Description: Byte array Tool class *@authorlky* @date October 26, 2015 * @vesion 1.0*/ Public classObjecttobytearray {Private StaticLog log = Logfactory.getlog (Objecttobytearray.class); Private StaticInteger max_length = 2048;//How many bytes are read from the stream each time /*** @Title: Getbytearray * @Description: Reads data from the input stream and returns a byte array *@paramIn input stream*/ Public Static byte[] Getbytearray (InputStream in) {Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); Try { byte[] buffer =New byte[Max_length]; intLen = 0; while(len = in.read (buffer, 0, buffer.length))! =-1) {baos.write (buffer,0, Len); Baos.flush (); Buffer=New byte[Max_length]; } } Catch(Exception e) {}finally { Try { if(In! =NULL) {in.close (); } if(BAOs! =NULL) {baos.close (); } } Catch(Exception E2) {Log.info ("BYTE stream off exception!!!"); } } returnBaos.tobytearray (); } /*** @Title: Objecttobyte * @Description: Convert object to byte array *@paramObject*/ Public Static byte[] Objecttobyte (Object object) {Bytearrayoutputstream BAOs=NULL; ObjectOutputStream Oos=NULL; Try{BAOs=NewBytearrayoutputstream (); Oos=NewObjectOutputStream (BAOs); Oos.writeobject (object); Oos.flush (); } Catch(Exception e) {log.info ("Object converted to byte array exception!!! "); } finally { Try { if(Oos! =NULL) {oos.close (); } if(BAOs! =NULL) {baos.close (); } } Catch(Exception E2) {Log.info ("BYTE stream off exception!!!"); } } returnBaos.tobytearray (); } /*** @Title: Bytearraytoobject * @Description: Converting byte arrays to objects *@paramBuffer*/ Public StaticObject Bytearraytoobject (byte[] buffer) {Object Object=NULL; Bytearrayinputstream Bais=NULL; ObjectInputStream OSS=NULL; Try{Bais=Newbytearrayinputstream (buffer); OSS=NewObjectInputStream (Bais); Object=Oss.readobject (); } Catch(Exception e) {log.info ("Object converted to byte array exception!!! "); } finally { Try { if(OSS! =NULL) {oss.close (); } if(Bais! =NULL) {bais.close (); } } Catch(Exception E2) {Log.info ("BYTE stream off exception!!!"); } } returnobject; } Public Static voidMain (String args[]) {Student Student=NewStudent (); Student.setid (1); Student.setlog ("Log"); Student.setname ("Lky"); SYSTEM.OUT.PRINTLN (student); byte[] buffer=Objecttobyte (student); System.out.println (buffer.length); System.out.println ((Student) bytearraytoobject (buffer)); }}
java--byte array input, output stream