我有一个xml文档被序列化为字节流并持久保存到数据库。我得到了字节流,但是如何将它再次转换为xml文件呢?
答案 0 :(得分: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)
答案 1 :(得分: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;
}
P.S。我从阁楼挖出的旧代码 - 需要现代化