利用JDOM把JPG图象数据写入XML一个简单例子

转载自: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;
  }

利用JDOM来写XML文件

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;
    }

  }


文件生成了,打开bb.xml可以看到BASE64的编码

第二步把bb.xml的数据还原

用JDOM解析bb.xml,读取CDATA对象,通过CDATA对象取得二进制数据,写文件完成。

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;
    }


posted on 2012-04-03 18:45  yang3wei  阅读(438)  评论(0编辑  收藏  举报