seasontop 发表于 2013-1-15 02:53:48

Base64 XML JDom 实例

问题:如何将二进制存入XML 然后传输倒别的地方,然后将其取出呢?

解答。我们写一段程序。
思路,
1 将图片存进XML文档的方式
答:将图片利用Base64编码成字符串形式,然后通过JDOM存储进XML
2 将图片从XML取出
答:通过JDOM取出图片编码的字符串,然后通过Base64解码成二进制形式

所以我们可以归纳出三个类
FileBase64.java 负责编码解码图片
ParseXML.java 读取XML文档,读出图片的字符串,解码成图片
OutputXML.java 将图片编码成字符串并放进XML文档

下面是源码。注释已经相当于讲解。

package www.websiteempire.cn;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/*
* 两个方法,binaryToString一个是将二进制编码成字符串的方法,其中MessageDigest是消息摘要
* 可要可不要。核心方法是使用BASE64Encoder的 方法对数据惊醒编码。
* 同理stringToBinary

*/
public class FileBase64
{
public static int MAX_BUFFER_SIZE = 524288; // default 512 kB
private int maxBufferSize = MAX_BUFFER_SIZE;
private String md5sum = null;
private int fileLength = -1;

public String fileToString(String path, String name)
   {

    return null;
   }

public String binaryToString(String path) throws IOException
   {
    File fm = new File(path);
    if (fm.isFile())
   {
      InputStream in = null;
      String ss = new String();
      MessageDigest md = null;

      try
       {
      in = new FileInputStream(fm);
      md = MessageDigest.getInstance("MD5");
      byte[] Buffer = new byte;
      int read = 0;
      int fileLength = 0;
      while ((read = in.read(Buffer)) != -1)
         {
          fileLength += read;
          md.update(Buffer, 0, read);
          if (read < maxBufferSize)
         {
            byte[] buf = new byte;
            System.arraycopy(Buffer, 0, buf, 0,
            read);
            Buffer = buf;
         }
          ss += new BASE64Encoder().encode(Buffer) + " ";
         }
      md5sum = new BASE64Encoder().encode(md.digest());
      return ss;
       } catch (FileNotFoundException e)
       {
      // TODO Auto-generated catch block
      e.printStackTrace();
       } catch (NoSuchAlgorithmException e)
       {
      // TODO Auto-generated catch block
      e.printStackTrace();
       }
       finally
   {
   try
   {
   if (in != null) in.close();
   }
   catch (Exception e)
   {
   e.printStackTrace();
   }
   }
   }

    return null;
   }



   public boolean stringToBinary(String path,String data)
    {
   OutputStream os=null;
   try
      {
       os=new FileOutputStream(new File(path));
       byte[] buf = new BASE64Decoder().decodeBuffer(data);
       MessageDigest md=MessageDigest.getInstance("md5");
       fileLength=-1;
       md5sum = null;
   if (buf != null)
   {
   os.write(buf);
   fileLength = buf.length;
   md5sum = new BASE64Encoder().encode(md.digest(buf));
   }
   else return false;

   return true;


      } catch (FileNotFoundException e)
      {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } catch (NoSuchAlgorithmException e)
       {
      // TODO Auto-generated catch block
      e.printStackTrace();
       } catch (IOException e)
       {
      // TODO Auto-generated catch block
      e.printStackTrace();
       }
       finally
      {
      try
      {
      if (os != null) os.close();
      }
      catch (Exception e)
      {
      e.printStackTrace();
      }
      }



   return false;
    }

   public int getMaxBufferSize()
    {
   return maxBufferSize;
    }

   public void setMaxBufferSize(int maxBufferSize)
    {
   this.maxBufferSize = maxBufferSize;
    }

   public String getMd5sum()
    {
   return md5sum;
    }

   public void setMd5sum(String md5sum)
    {
   this.md5sum = md5sum;
    }

   public int getFileLength()
    {
   return fileLength;
    }

   public void setFileLength(int fileLength)
    {
   this.fileLength = fileLength;
    }
   //main test
//   public static void main(String[] args)
//    {
//   String path="G:\\workspace\\software\\src\\splash.jpg";
//   FileBase64 fb=new FileBase64();
//   String temp=null;
//   try
//   {
//      temp=fb.fileToString(path);
//   } catch (IOException e)
//   {
//      // TODO Auto-generated catch block
//      e.printStackTrace();
//   }
//   System.out.println(temp);
////   try
////      {
////       FileOutputStream fos=new FileOutputStream(new File("e:/splash.txt"));
////       fos.write(temp.getBytes());
////       fos.close();
////      } catch (FileNotFoundException e)
////      {
////       // TODO Auto-generated catch block
////       e.printStackTrace();
////      }
//////   System.out.println(fb.getFileLength());
//////   System.out.println(fb.getMd5sum());
//////   fb.stringToFile("e:\\splash.jpg", temp);
//// catch (IOException e)
////       {
////      // TODO Auto-generated catch block
////      e.printStackTrace();
////       }
////   
//    }

}

_---------------------------------------------------------------


package www.websiteempire.cn;

import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ParseXML
{

/**
* @param args这个文件比较简单就是读取XML文件并且输出图片
*/

public static void main(String[] args)
   {
   try
    {
   SAXBuilder parser=new SAXBuilder();
   Document document=parser.build("e:/cc.xml");
   process(document.getRootElement());
    } catch (JDOMException e)
    {
   // TODO Auto-generated catch block
   e.printStackTrace();
    } catch (IOException e)
    {
   // TODO Auto-generated catch block
   e.printStackTrace();
    }

   }

public static void process(Element element)
   {
Element img=element.getChild("img");
String temp=img.getText();
    String path="e:/cc.jpg";
   FileBase64 fb=new FileBase64();
   fb.stringToBinary(path,temp);

   }



}
---------------------------------------------------------------------

package www.websiteempire.cn;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class OutputXML
{

/**
* 这段是测试代码。你可以根据你的要求自己写一个。为了测试效果,你可以
* 直接修改路径
*
*/

public static void main(String[] args)
   {

    String path="e:/cc.jpg";
   FileBase64 fb=new FileBase64();
   OutputXML outputXml=new OutputXML();

   String temp=null;
   try
   {
      temp=fb.binaryToString(path);
   } catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
   String img=temp;
   String description="you can ";
   Date CDate=new Date(System.currentTimeMillis());
   String ower="websiteempire.cn";
   Document doc=outputXml.constructXML(img, description, CDate, ower);
   outputXml.WriteXML(doc, "e:/cc.xml");





   }
/*
* 这段代码主要是用来生成一个XML文档,其中包含的元素有 imgElement图片结点,descriptionElement描述图片的文字描述,
* CDateElment图片的穿件日期, OwerElment拥有者
*/

public Document constructXML(String img, String description,
    Date CDate, String ower)

   {
    Element root = new Element("websiteempire_cn");

    Element imgElement = new Element("img");
    imgElement.setText(img);

    Element descriptionElement = new Element("description");
    descriptionElement.setText(description);

    Element CDateElement = new Element("CDate");
    CDateElement.setText(CDate.toGMTString());

    Element owerElement = new Element("ower");
    owerElement.setText(ower);

    root.addContent(imgElement);
    root.addContent(descriptionElement);
    root.addContent(CDateElement);
    root.addContent(owerElement);

    Document doc = new Document(root);
    return doc;

   }
/*
* 将XML文档保存成一个文件。
*/

public void WriteXML(Document doc,String path)
   {
    File file=new File(path);
    try
   {
      FileOutputStream fos=new FileOutputStream(file);

      XMLOutputter out=new XMLOutputter();
      out.output(doc, fos);
   } catch (FileNotFoundException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   } catch (IOException e)
      {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }


   }

}
页: [1]
查看完整版本: Base64 XML JDom 实例