您的位置:首页 > Web前端

用JDOM+Base64编码存储和读取图片进XML

2006-11-15 18:03 465 查看
 存信息:


import java.io.FileOutputStream;


import java.util.Iterator;




import org.jdom.*;


import org.jdom.output.XMLOutputter;




import filemanager.FileBase64;






/** *//**


 * @author Develop


 *


 * TODO To change the template for this generated type comment go to


 * Window - Preferences - Java - Code Style - Code Templates


 */




public class BildSpeichern ...{


    




    public BildSpeichern() ...{


        }


    


    


    




    public void makeImageXml(DicTemp dic) throws Exception...{


        


        // datei definition


        String srcpath = "c:/baidu.gif";


        String targpath = "c:/imgspeichern.xml";


        String li = "Welcome";


        String ni = "Test Nachricht";


//         Base64 kodierung


        FileBase64 fb = new FileBase64();


        long start = System.currentTimeMillis();


        String f = fb.fileToString(srcpath);


        long stop = System.currentTimeMillis();


        System.out.println("die kodierte Bild (binär) zeigt:");


        Sys
21a72
tem.out.println(f);


        Iterator dicIt = dic.getIterator();


        // Head-Informationen erstellen


        


        




        


        // Root erzeugen


        Document xmlDoc = new Document();


        


        


        Element content=new Element("Content");


        xmlDoc.setRootElement(content);


        


        


        


        


        //Knote erzeugen


        Element wa = new Element("WebAdmin");


        content.addContent(wa);


        Element lb = new Element("Label");


        wa.addContent(lb);


        String LabelInfo = new String(li.getBytes("UTF-8"));


        lb.addContent(LabelInfo);


        


        Element wd = new Element("WebDe");


        content.addContent(wd);


        Element nt = new Element("Nachricht");


        wd.addContent(nt);


        Element bd = new Element("Bild");


        wd.addContent(bd);


        


        String NtInfo = new String(ni.getBytes("UTF-8"));


        String BdInfo = new String(f.getBytes("UTF-8"));


        nt.addContent(NtInfo);


        bd.addContent(BdInfo);




        /**//*


         * xmlPhoto.setAttribute("name",srcpath);


        xmlPhoto.setAttribute("src","http://bw-shanghai.de/baidu.gif");*/


        


        




        


        XMLOutputter outp = new XMLOutputter("  ",true,"UTF-8"); 


         outp.output(xmlDoc, new FileOutputStream(targpath)); 


        System.out.println("XML Created!!");


        


        




      /**//*


       *  XMLOutputter   outp=new   XMLOutputter();   


    


  Format   format=Format.getPrettyFormat();   


  format.setEncoding("GBK");   


  outp.setFormat(format);   


  outp.output(doc,System.out);   


       * 


       * */


        


    }






    public static void main(String[] args) ...{


        BildSpeichern bs = new BildSpeichern();


        DicTemp dic = new DicTemp();


        




        try...{            


            bs.makeImageXml(dic);




        }catch (Exception ex)...{System.out.println("Fehler");};


    }


}

 

读出信息中的图片:

 


import java.io.File;


import java.io.IOException;


import org.jdom.Document;


import org.jdom.Element;


import org.jdom.JDOMException;


import org.jdom.input.SAXBuilder;




import filemanager.FileBase64;






/** *//**


 * @author Develop


 *


 * TODO To change the template for this generated type comment go to


 * Window - Preferences - Java - Code Style - Code Templates


 */




public class BildAuslesen ...{




    public BildAuslesen()...{        


    }


    




    public void InfoExtrahieren() throws JDOMException, IOException...{


        


        String xmlfile = "c:/imgspeichern.xml";


        SAXBuilder builder = new SAXBuilder();


        Document doc = builder.build(new File(xmlfile));


        


        Element content=doc.getRootElement();


        


        Element wd = content.getChild("WebDe");


        String bd = wd.getChildText("Bild");


        


        FileBase64 fb = new FileBase64();


        long start = System.currentTimeMillis();


        fb.stringToFile("c:/x.jpg", bd);


        long stop = System.currentTimeMillis(); 


        


        


    }








    public static void main(String[] args) ...{


        BildAuslesen ba = new BildAuslesen();


        


        




        try...{


            ba.InfoExtrahieren();


            System.out.println("Doc Created!!");




        }catch (Exception ex)...{System.out.println("Fehler: Content auslesen");};


                




    }


}

说明:

其中主要用两个方法:filetostring(),和stringtofile()

 




import java.io.File;


import java.io.FileInputStream;


import java.io.FileOutputStream;


import java.io.InputStream;


import java.io.OutputStream;


import java.security.MessageDigest;




import sun.misc.BASE64Decoder;


import sun.misc.BASE64Encoder;






/** *//**


 * Converts file to string with base64encoder and string to file with base64decoder.


 * 


 * The MAX_BUFFER defines the speed of fileToString function!


 * Bigger Value -> faster, more than filesize -> max. speed. 


 * 


 * Generates MD5 checksumms!


 * 


 * MAX_BUFFER_SIZE -> used by stream operations.


 */


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;


    private FileManager fm = new FileManager();






    /** *//**


     * Convert File to Base64 Encoded String.


     * 


     * Generate MD5 Checksum and fileLenght.


     * 


     * @param path Filepath.


     * @param name Filename.


     * @return Returns Base64 Encoded String, else null.


     */


    public String fileToString(String path, String name)




    ...{


        return fileToString(fm.makeAbstractPath(path, name));


    }






    /** *//**


     * Convert File to Base64 Encoded String.


     * 


     * Generate MD5 Checksum and fileLenght.


     * 


     * @param path Abstract Filepath.


     * @return Returns Base64 Encoded String, else null.


     */


    public String fileToString(String path)




    ...{


        if (fm.isFile(path))




        ...{


            InputStream in = null;


            try




            ...{


                String str = new String();


                File f = new File(path);


                in = new FileInputStream(f.getPath());


                MessageDigest md = MessageDigest.getInstance("MD5");


                byte buffer[] = new byte[maxBufferSize];


                int read = 0;


                fileLength = 0;


                while ((read = in.read(buffer)) != -1)




                ...{


                    fileLength += read;


                    md.update(buffer, 0, read);


                    if (read < maxBufferSize) // trick 17, if buffer size < max. size :-)




                    ...{


                        byte[] buf = new byte[read];


                        System.arraycopy(buffer, 0, buf, 0, read);


                        buffer = buf;


                    }


                    str += new BASE64Encoder().encode(buffer) + " ";


                }


                md5sum = new BASE64Encoder().encode(md.digest());




                return str;


            }


            catch (Exception e)




            ...{


                e.printStackTrace();


            }


            finally




            ...{


                try




                ...{


                    if (in != null) in.close();


                }


                catch (Exception e)




                ...{


                    e.printStackTrace();


                }


            }


        }




        return null;


    }






    /** *//**


     * Convert Base64 String to File. Overwrites destination!


     * 


     * @param path Filepath.


     * @param name Filename.


     * @param data Base64 Encoded String.


     * @return Returns true if ok, else false.


     */


    public boolean stringToFile(String path, String name, String data)




    ...{


        return stringToFile(fm.makeAbstractPath(path, name), data);


    }






    /** *//**


     * Convert Base64 String to File. Overwrites destination!


     * 


     * @param path Abstract Filepath.


     * @param data Base64 Encoded String.


     * @return Returns true if ok, else false.


     */


    public boolean stringToFile(String path, String data)




    ...{


        OutputStream out = null;


        try




        ...{


            out = new FileOutputStream(path);




            MessageDigest md = MessageDigest.getInstance("MD5");


            byte[] buf = new BASE64Decoder().decodeBuffer(data);




            fileLength = -1;


            md5sum = null;


            if (buf != null)




            ...{


                out.write(buf);


                fileLength = buf.length;


                md5sum = new BASE64Encoder().encode(md.digest(buf));


            }


            else return false;




            return true;


        }


        catch (Exception e)




        ...{


            e.printStackTrace();


        }


        finally




        ...{


            try




            ...{


                if (out != null) out.close();


            }


            catch (Exception e)




            ...{


                e.printStackTrace();


            }


        }




        return false;


    }




    // getter and setter






    /** *//**


     * @return Returns the maxBufferSize.


     */


    public int getMaxBufferSize()




    ...{


        return maxBufferSize;


    }






    /** *//**


     * @param maxBufferSize The maxBufferSize to set.


     */


    public void setMaxBufferSize(int maxBufferSize)




    ...{


        if (maxBufferSize > 0) this.maxBufferSize = maxBufferSize;


    }






    /** *//**


     * @return Returns the fileLength.


     */


    public int getFileLength()




    ...{


        return fileLength;


    }






    /** *//**


     * @return Returns the md5sum.


     */


    public String getMd5sum()




    ...{


        return md5sum;


    }




    // main for testing




    public static void main(String[] args)




    ...{


        FileBase64 fb = new FileBase64();




        //fb.setMaxBufferSize(FileBase64.MAX_BUFFER_SIZE*20);


        


        //String f = fb.fileToString("C:/modem", "gnupg.doc");


        long start = System.currentTimeMillis();


        String f = fb.fileToString("C:/modem/JProjectNico.zip");


        long stop = System.currentTimeMillis();




        double t1 = (stop - start) / 1000.0;


        System.out.println("# fileToString -> " + (t1) + " s");




        //System.out.println(f);


        System.out.println(f.length());


        System.out.println(fb.getFileLength());


        System.out.println(fb.getMd5sum());




        start = System.currentTimeMillis();


        fb.stringToFile("C:/modem/xxxxx.doc", f);


        stop = System.currentTimeMillis();




        double t2 = (stop - start) / 1000.0;


        System.out.println("# stringToFile -> " + (t2) + " s");




        System.out.println(fb.getFileLength());


        System.out.println(fb.getMd5sum());




        System.out.println("## f2s = " + (fb.getFileLength() / 1048576.0) / t1 + " MB/s # s2f = " + (fb.getFileLength() / 1048576.0) / t2 + " MB/s");


    }


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐