我希望能够转换存储从BufferedReader读取的文件内容的ArrayList<String>
,然后将内容转换为byte[],以便使用Java类对其进行加密。
我尝试过使用.getBytes()
,但它不起作用,因为我认为我需要首先转换ArrayList,而我在弄清楚如何做到这一点时遇到了麻烦。
代码:
// File variable
private 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));
}
非常感谢,提前!
发布于 2019-02-12 15:51:12
连接字符串或创建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();
发布于 2019-02-12 15:58:22
为什么你要把它读成字符串,然后把它转换成字节数组呢?从Java 7开始,您可以执行以下操作:
byte[] input= Files.readAllBytes(new File(userFile.toPath());
然后将该内容传递给Cipher。
byte[] output = cipher.doFinal(input);
此外,您可以考虑使用流(InputStream和CipherOutputStream),而不是将整个文件加载到内存中,以防您需要处理大文件。
发布于 2019-02-12 15:48:18
因此,完整的ArrayList
实际上是一个单独的String
一种简单的方法是将其中的所有Strings
合并为一个,然后对其调用.getBytes()
。
https://stackoverflow.com/questions/54645112
复制相似问题