加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml 二进制数据 传输处理

发布时间:2020-12-16 05:18:21 所属栏目:百科 来源:网络整理
导读:XML中的数据无论采用CASTOR还是JDOM框架都可以进行对图片、文件的传输和处理。在内存中他们以byte[]来表示和存储。下面以文件的方式进行了说明,特别注意的是对于二进制要采用64编码的方式表示在XML文件中。 import org.jdom.Document; import org.jdom.Eleme
XML中的数据无论采用CASTOR还是JDOM框架都可以进行对图片、文件的传输和处理。在内存中他们以byte[]来表示和存储。下面以文件的方式进行了说明,特别注意的是对于二进制要采用64编码的方式表示在XML文件中。
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.input.DOMBuilder;
import org.jdom.output.XMLOutputter;
import org.apache.xerces.impl.dv.util.Base64;
import java.io.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class My64DomTest {
public static void writeXml() {
String content = "";
try {
//将文件读入内存字节数组
InputStream in = new FileInputStream("e:/test.JPG");
byte[] data = new byte[1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
while ((len = in.read(data)) > 0) {
baos.write(data,len);
}
in.close();
//对内存数据进行64编码
BASE64Encoder be = new BASE64Encoder();
content = be.encode(baos.toByteArray());
} catch (IOException ex) {
System.out.println("++++++++++++++ Get inputStream error +++++++++++++++++");
ex.printStackTrace();
}
Element carElement = new Element("car");
Document myDocument = new Document(carElement);
Element make = new Element("make");
make.addContent(content);
carElement.addContent(make);
//将编码后的数据生成xml文件输出
try {
XMLOutputter outputter = new XMLOutputter(" ",true);
FileOutputStream out = new FileOutputStream("e:/test.xml");
outputter.output(myDocument,out);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public static void readXml() {
try {
//这里不要使用SAXBuilder,否则将很慢
//读入xml文件数据
DOMBuilder builder = new DOMBuilder();
Document anotherDocument = builder.build(new File("e:/test.xml"));
Element carElement = anotherDocument.getRootElement();
Element make = carElement.getChild("make");
String aa = make.getText();
//BASE64Decoder bd = new BASE64Decoder();
//将图片数据转码后写入文件
try {
byte[] bbs = Base64.decode(aa);
FileOutputStream out = new FileOutputStream("e:/test1.jpg");
out.write(bbs);
out.close();
} catch (IOException e) {
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
特别注意注释地方的处理。验证通过完全可以使用。
关于xml的传输和处理的问题虽然有了一定的处理经验但还是应该抽时间在深入的研究一下!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读