我希望能夠轉換一個ArrayList<String>存儲從 BufferedReader 讀取的文件內容的文件,然后將內容轉換為 byte[] 以允許使用 Java 的 Cipher 類對其進行加密。我嘗試過使用.getBytes(),但它不起作用,因為我認為我需要先轉換 ArrayList,而且我在弄清楚如何做到這一點時遇到了麻煩。代碼:// File variableprivate static String file;// From main()file = args[2];private static void sendData(SecretKey desedeKey, DataOutputStream dos) throws Exception { ArrayList<String> fileString = new ArrayList<String>(); String line; String userFile = file + ".txt"; BufferedReader in = new BufferedReader(new FileReader(userFile)); while ((line = in.readLine()) != null) { fileString.add(line.getBytes()); //error here } Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, desedeKey); byte[] output = cipher.doFinal(fileString.getBytes("UTF-8")); //error here dos.writeInt(output.length); dos.write(output); System.out.println("Encrypted Data: " + Arrays.toString(output)); }提前謝謝了!
3 回答
MYYA
TA貢獻1868條經驗 獲得超4個贊
連接字符串,或創(chuàng)建一個StringBuffer.
StringBuffer buffer = new StringBuffer();
String line;
String userFile = file + ".txt";
BufferedReader in = new BufferedReader(new FileReader(userFile));
while ((line = in.readLine()) != null) {
buffer.append(line); //error here
}
byte[] bytes = buffer.toString().getBytes();
慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
為什么要將其讀取為字符串并將其轉換為字節(jié)數(shù)組?從 Java 7 開始,您可以執(zhí)行以下操作:
byte[] input= Files.readAllBytes(new File(userFile.toPath());
然后將該內容傳遞給密碼。
byte[] output = cipher.doFinal(input);
您也可以考慮使用流(InputStream 和 CipherOutputStream)而不是將整個文件加載到內存中,以防您需要處理大文件。
一只名叫tom的貓
TA貢獻1906條經驗 獲得超3個贊
那么,fullArrayList實際上是 singleString嗎?
一種直接的方法是將其中的所有Strings內容合并為一個,然后調用.getBytes()它。
添加回答
舉報
0/150
提交
取消
