2014-12-24 44 views
1

我有一個base64編碼的字符串。看起來像這樣base 64解碼並寫入doc文件

UEsDBBQABgAIAAAAIQDhD46/jQEAACkGAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA . 

解碼字符串並使用FileWriter將其寫入字文件。但是,當我試圖打開文檔文件時,我收到一個錯誤,指出損壞的數據。

我想知道在解碼數據後需要將內容寫入word文檔的步驟是什麼。下面是我所做的和錯誤的代碼。

 byte[] encodedBytes = stringBase64.getBytes(); 
    byte[] decodedBytes = Base64.decodeBase64(encodedBytes); 
    String decodeString = new String(decodedBytes); 
    filewriter = new java.io.FileWriter("F:\xxx.docx」); 
    BufferedWriter bw = new BufferedWriter(fw); 
    bw.write(decodeString); 
+1

您是否在寫完bw.close()之後關閉了緩衝寫入器? – sol4me

+0

嘗試在寫入數據後關閉文件,bw.close(); –

回答

3

解碼數據不是純文本數據 - 它只是二進制數據。所以用FileStream寫它,而不是一個FileWriter

// If your Base64 class doesn't have a decode method taking a string, 
// find a better one! 
byte[] decodedBytes = Base64.decodeBase64(stringBase64); 
// Note the try-with-resources block here, to close the stream automatically 
try (OutputStream stream = new FileOutputStream("F:\\xxx.doc")) { 
    stream.write(decodedBytes); 
} 

甚至更​​好:

byte[] decodedBytes = Base64.decodeBase64(stringBase64); 
Files.write(Paths.get("F:\\xxx.doc"), decodedBytes); 
+0

謝謝喬恩。使用FileStream編寫它們工作。 – Sumanth

2

請看看。

byte[] encodedBytes = /* your encoded bytes*/ 

// Decode data on other side, by processing encoded data 
    byte[] decodedBytes= Base64.decodeBase64(encodedBytes); 

    String yourValue=new String(decodedBytes); 
    System.out.println("Decoded String is " + yourValue); 

現在進一步,您可以將此字符串寫入文件並進一步閱讀。

+0

請考慮包括一些關於您的答案的信息,而不是簡單地發佈代碼。我們嘗試提供的不僅僅是「修復」,而是幫助人們學習。你應該解釋原始代碼中的錯誤,你做了什麼不同,以及爲什麼你的改變起作用。 –