Treatment method of binary data in XML
In XML, all data is displayed in the form of text, but binary data cannot be represented directly in the text format, how is the XML handle binary data? Let's discuss it.
For simple and versatility, XML is designed to represent data in text format. In XML, all data is stored in text format, and binary data is no exception. In XML, binary data should also be encoded into the format of the text, send to the destination. After the purpose of the object received this text binary data, the corresponding binary data is solved with the same decoding program. Of course, the data is originally format, name and other auxiliary information must be sent together as related information. General binary data encodes into base64 format, it is easy to encode and decoding, and the disadvantage is that a 33% storage space is taken than pure binary.
The following is a specific program implementation:
<% @ Page ContentType = "text / html; charset = GB2312"%>
<% @ Page Import = "java.io. *"%>
<%
String Ret = new string ();
Try
{
InputStream IN = New FileInputStream ("c: //aaa.doc");
BYTE [] bytes = new byte [in.available ()];
In.read (bytes);
Ret = new sun.misc.base64encoder (). eNCode (bytes); // specific coding method
In.Close ();
}
Catch (FilenotFoundException E)
{
E.PrintStackTrace ();
}
Catch (java.io ioexception ex)
{
EX.PrintStackTrace ();
}
%>
RET is the final result, and you can send it with a standard XML in the encoding. After sending to the destination, the corresponding decoding of the data can be decoded to get the original binaries, the decoded code is as follows:
<% @ Page ContentType = "text / html; charset = GB2312"%>
<% @ Page Import = "java.io. *"%>
<%
Byte [] bytes = new sun.misc.base64decoder (). DecodeBuffer (RET);
Java.io.byteaRrayinputStream Instream = New java.io.byteArrayInputStream (Bytes);
Byte [] buffer = new byte [1444];
FileOutputStream Fs = New FileOutputStream ("D: //aaa.doc");
INT BYTESUM = 0;
INT BYTEREAD = 0;
While ((Byteread = Instream.read (buffer)! = - 1)
{
Bytesum = byteread;
fs.write (buffer, 0, byteread);
}
%>
Base64 can handle uncommon data. If you want to move a lot of data, you should use other alternative methods when considering space / time efficiency.