2010-04-20 7 views
1

J'ai un document XML qui a été sérialisé dans un flux d'octets et conservé dans une base de données. Je récupère le flux d'octets, mais comment puis-je le convertir dans un fichier XML?Conversion de ByteArrayInputStream en fichier xml

+0

Quel est le format du flux d'octets? n'est-ce pas en XML? –

Répondre

0

Voici quelques méthodes pour convertir dans les deux sens de byte [] et le dos. Bien sûr, l'objet peut être une chaîne

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

post-scriptum Ce vieux code que j'ai creusé dans le grenier - A besoin d'être modernisé