Test procedures, found from the intranet received from the external network application size and the original application size, debugging for a long time to find that the byte array and string mutual transformation has arisen. According to the project needs, when the external network sends the application, first will convert the byte[] to the string, then the intranet receives, then transforms the string to byte[], but because of the coding problem, obtains byte[] and the original byte[] is not same, causes receives the file size error, cannot carry on the follow-up operation. In order to obtain the original byte[], the new SUN.MISC.BASE64 encoding method can be used. The previous article has mentioned how to prepare for the use of new sun.misc.BASE64.
1. Convert byte[] to string:
byte [] before=newbyte[] {80, 75, 3, 4, 10, 60, 82,-83, 68, 8, 0, 28, 0, 80, 97}; Base64encoder enc=New base64encoder (); String Mes=enc.encodebuffer (before); Using BASE64 encoding |
2, restore the string to byte[]
Base64decoder dec=New base64decoder (); byte []after=null; Try { After =dec.decodebuffer (MES);//Use BASE64 decoding } catch (Ioexceptione) { TODO auto-generated Catch block E.printstacktrace (); } |
3. Java Test Code
import Java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import Sun.misc.BASE64Decoder; import Sun.misc.BASE64Encoder; Publicclass Test2 { publicstatic void main (string[] args) { byte []before=newbyte[] {80, 75, 3, 4, 10, 60, 82,-83, 68, 8, 0, 28, 0, 80, 97, 121, 108, 108}; Base64encoder enc=New base64encoder (); String Mes=enc.encodebuffer (before); Using BASE64 encoding Base64decoder dec=New base64decoder (); byte []after=null; Try { After =dec.decodebuffer (MES);//Use BASE64 decoding } catch (Ioexceptione) { TODO auto-generated Catch block E.printstacktrace (); } System. out. println ("before=" +arrays.tostring (before)); System. out. println (after = "+arrays.tostring"); } } |
4, the results of the operation, byte[] successfully restored.
5, in addition, can also use Datatypeconverter.