2013-05-14 53 views
1

我需要追加二進制數據到文件,但在此數據是一個XML頭。整個文件不會是正確的XML文件,但它必須像下列正確的XML標題:追加二進制數據到序列化的XML頭

<EncryptedFileHeader> 
    <Algorithm>name</Algorithm> 
    <KeySize>256</KeySize> 
    <SubblockLength>64</SubblockLength> 
    <CipherMode>ECB</CipherMode> 
    <sessionKey>sessionKey</sessionKey> 
</EncryptedFileHeader> 
*binary data* 

XML頭我JAXB編組容易,並且更容易將做用base64和存儲在添加此二進制數據注意在xml中。但這是一條線索。我必須將它存儲爲二進制文件以節省base64使用的33%空間。

所以問題是如何添加這些數據,當然以後再讀一遍(serialize/deserialize)?

另一個問題是如何從第一行文件中刪除?

我試着使用:

marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE); 

但它拋出一個異常:

javax.xml.bind.PropertyException:名稱:com.sun.xml.bind.xmlDeclaration值:假 在javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(AbstractMarshallerImpl.java:358) 在com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(MarshallerImpl.java:527)

由於

+0

您可以改爲使用標準的'JAXB_FRAGMENT'屬性。 – 2013-05-14 11:12:49

+0

您可能會發現以下有用的信息:http://blog.bdoughan.com/2011/03/jaxb-web-services-and-binary-data.html – 2013-05-14 12:07:53

回答

0

Actualy我解決了這個通過串行化與JAXB XML頭,那麼附加的二進制數據(字節陣列)到現有的文件。 從文件中讀取用緩衝讀取如下:

BufferedReader reader = new BufferedReader(new FileReader("filepath")); 
     String line, results = ""; 
     while ((line = reader.readLine()) != null) { 
      results += line; 
     } 
     reader.close(); 

     String[] splited = results.split("</EncryptedFileHeader>"); 
     splited[0] += "</EncryptedFileHeader>"; 
     String s0 = splited[0]; 
     String s1 = new String(splited[1]); 
     ByteArrayInputStream bais = new ByteArrayInputStream(s0.getBytes()); 

現在,我得到與第二splited串S1的一個問題,它從由數據「byteArrayOutputStream.toByteArray();」。現在我必須將數據從這個字符串傳輸到字節數組。來源:

「鹵化銀

喜歡的東西:
[39,-63,-116,65,-123,-114,27, - 115,-2,103,-64,88,-99,-96,-26,-12]

我試過了(在同一臺機器上): byte [] bytes = s1.getBytes();

但字節數組是不同的,並返回34字節,而不是16.我讀了很多關於編碼,但仍然不知道。

編輯:

具有不同數量的字節的問題是由於由字符和字節流中的不同的表示新行的。

相關問題