2012-09-01 29 views
5

我需要通過加密將字符串數組列表存儲在文件中。然後我解密文件內容並將其恢復到數組列表。但是,當我解密內容時,內容中有'Null'塊。沒有'空'塊,其餘的文本與我編碼的相同。加密並解密ArrayList <String>

public static void encryptFile(List<String> moduleList, File fileOut) { 
    try { 
     OutputStream out = new FileOutputStream(fileOut); 
     out = new CipherOutputStream(out, encryptCipher); 
     StringBuilder moduleSet = new StringBuilder(); 
     for (String module : moduleList) { 
      moduleSet.append(module + "#"); 
     } 
     out.write(moduleSet.toString().getBytes(Charset.forName("UTF-8"))); 
     out.flush(); 
     out.close(); 
    } catch (java.io.IOException ex) { 
     System.out.println("Exception: " + ex.getMessage()); 
    } 
} 

public static List<String> decryptFile(File fileIn) { 
    List<String> moduleList = new ArrayList<String>(); 
    byte[] buf = new byte[16]; 

    try { 
     InputStream in = new FileInputStream(fileIn); 
     in = new CipherInputStream(in, decryptCipher); 

     int numRead = 0; 
     int counter = 0; 
     StringBuilder moduleSet = new StringBuilder(); 
     while ((numRead = in.read(buf)) >= 0) { 
      counter++; 
      moduleSet.append(new String(buf)); 
     } 

     String[] blocks = moduleSet.split("#"); 
     System.out.println("Items: " + blocks.length); 

    } catch (java.io.IOException ex) { 
     System.out.println("Exception: " + ex.getMessage()); 
    } 
    return moduleList; 
} 

我用UTF-16嘗試,因爲串在Java編碼UTF-16,但它只會讓輸出最差。 您的建議將不勝感激... 感謝

+6

絕不拍照源代碼併發布它們。將源代碼複製+粘貼到您的問題中,或花時間輸入。 – Jeffrey

+0

問題可能位於位置(242,137) – Alex

+1

@Jeffrey如果可能,我會去複製/粘貼。如果因爲我在Kindle上或其他原因而無法實現這一點,我可能會延遲詢問一個問題,直到我回到桌面開發機器。當(重新)輸入代碼時,太多的錯誤會蔓延。 –

回答

4

我會撕裂了,你轉換你的清單內容,並從字符串的代碼,並與ObjectOutputStream替換爲:

FileOutputStream out1 = new FileOutputStream(fileOut); 
CipherOutputStream out2 = new CipherOutputStream(out1, encryptCipher); 
ObjectOutputStream out3 = new ObjectOutputStream(out2); 
out3.writeObject(moduleList); 

然後,閱讀返回:

FileInputStream in1 = new FileInputStream(fileIn); 
CipherInputStream in2 = new CipherInputStream(in1, decryptCipher); 
ObjectInputStream in3 = new ObjectInputStream(in2); 
moduleList = (Set<String>)in3.readObject() 
+0

是的,它的工作。通過使用你的方式,它不需要遍歷列表中的每個字符串併發送。所以我根本不需要考慮編碼的東西。我可以將它作爲一個對象發送並輕鬆閱讀。它減少了大量的代碼行。謝謝 – Anuruddha