我希望能够转换一个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个赞
连接字符串,或创建一个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个赞
为什么要将其读取为字符串并将其转换为字节数组?从 Java 7 开始,您可以执行以下操作:
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
提交
取消