转载自:http://www.cjsdn.net/post/view?bid=5&id=45013&sty=1&tpg=11&age=0
代码在JBUILDER上测试过
第一步
首先读取图象文件
public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { return null; } byte[] bytes = new byte[ (int) length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } is.close(); return bytes; }
public String getBinaryFile(java.io.File file) { String result = ""; try { result = new BASE64Encoder().encode(this.getBytesFromFile(file)); } catch (Exception exp) { JOptionPane.showMessageDialog(this, exp); return null; } return result; }
try { InputStream is = new FileInputStream(jpgFile); OutputStream out = new FileOutputStream("E:\\bb.xml"); BufferedInputStream bis = new BufferedInputStream(is); Element rootElement = new Element("root"); Document myDocument = new Document(rootElement); rootElement.addContent(new CDATA(this.getBinaryFile(jpgFile))); XMLOutputter outputter = new XMLOutputter(" ", true); outputter.output(myDocument, out); bis.close(); is.close(); out.close(); } catch (Exception ee) { JOptionPane.showMessageDialog(this, "file can't be writed"); return; } }
CDATA cdata ; try { SAXBuilder builder = new SAXBuilder(); Document ad = builder.build(xmlFile); Element rootElement = ad.getRootElement(); java.util.List list = rootElement.getMixedContent(); java.util.Iterator itr = list.iterator(); FileOutputStream fout = new FileOutputStream("E:\\1.jpg"); while(itr.hasNext()) { Object o = itr.next(); if (o instanceof CDATA) { cdata = (CDATA)o; fout.write(new sun.misc.BASE64Decoder().decodeBuffer(cdata.getText())); fout.close(); break; } } } catch (Exception eep) { JOptionPane.showMessageDialog(this, "read xml error"); return; }