将ByteArrayInputStream转换为xml文件

问题描述 投票:1回答:2

我有一个xml文档,序列化为字节流并持久保存到数据库。我得到了字节流,但是如何将它再次转换为xml文件呢?

java xml bytearray
2个回答
0
投票

它实际上取决于XML如何序列化为字节流等,但您可能想看一下the SAXParser类,尤其是[parse()方法] [2]。

[2]:http://java.sun.com/javase/6/docs/api/javax/xml/parsers/SAXParser.html#parse(java.io.InputStream,org.xml.sax.helpers.DefaultHandler)


0
投票

这里有几种来回转换为byte []和返回的方法。当然,Object可以是String

   public static Object byteArrayToObject(byte[] data)
   {
      Object retObject = null;
      if (data != null)
      {
         ByteArrayInputStream bis = null;
         ObjectInputStream ois = null;
         try
         {
            bis = new ByteArrayInputStream(data);
            ois = new ObjectInputStream(bis);

            retObject = ois.readObject();
         }
         catch(StreamCorruptedException e)
         {
            e.printStackTrace(System.out);
         }
         catch(OptionalDataException e)
         {
            e.printStackTrace(System.out);
         }
         catch(IOException e)
         {
            e.printStackTrace(System.out);
         }
         catch(ClassNotFoundException e)
         {
            e.printStackTrace(System.out);
         }
         finally
         {
            try
            {
               bis.close();
            }
            catch(IOException ex)
            {
               ex.printStackTrace(System.out);
            }

            try
            {
               ois.close();
            }
            catch(IOException ex)
            {
               ex.printStackTrace(System.out);
            }
         }
      }
      return retObject;
   }

   public static byte[] objectToByteArray(Object anObject)
   {
      byte[] results = null;
      if (anObject != null)
      {
         // create a byte stream to hold the encoded object
         ByteArrayOutputStream bytes = new ByteArrayOutputStream();

         try
         {
            // create a stream to write the object
            ObjectOutputStream ostrm = new ObjectOutputStream(bytes);

            // write the object
            ostrm.writeObject(anObject);

            // ensure that the entire object is written
            ostrm.flush();

            results = bytes.toByteArray();

            try
            {
               ostrm.close();
            }
            catch (IOException e)
            {
            }

            try
            {
               bytes.close();
            }
            catch (IOException e)
            {
            }
         }
         catch (IOException e)
         {
            e.printStackTrace(System.out);
         }
      }
      return results;
   }

附:我从阁楼挖出的旧代码 - 需要现代化

© www.soinside.com 2019 - 2024. All rights reserved.