[英]Convert ArrayList<String> to byte[]
我希望能够转换一个ArrayList<String>
,该ArrayList<String>
存储从BufferedReader读取的文件的内容,然后将内容转换为byte []以允许使用Java的Cipher类进行加密。
我尝试使用.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));
}
提前谢谢了!
为什么要将其读取为字符串并将其转换为字节数组? 从Java 7开始,您可以执行以下操作:
byte[] input= Files.readAllBytes(new File(userFile.toPath());
然后将该内容传递给密码。
byte[] output = cipher.doFinal(input);
另外,如果需要处理大文件,则可以考虑使用流(InputStream和CipherOutputStream),而不是将整个文件加载到内存中。
连接字符串,或创建一个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();
因此,完整的ArrayList
实际上是单个String
?
一种简单的方法是将其中的所有Strings
合并为一个,然后在其上调用.getBytes()
。
为什么要使用ArrayList。 只需使用StringBuffer并将文件的完整内容保存为单个字符串即可。
将所有字符串合并为Like
String anyName = allstring;
然后叫这个
anyName.getBytes();
它会帮助你。
您可以尝试利用Java的序列化功能,并使用包裹在ByteOutputStream周围的ObjectOutputStream:
try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout)) {
out.writeObject(list);
out.flush();
byte[] data = bout.toByteArray();
} catch (IOException e) {
// Do something with the exception
}
这种方法的缺点是字节数组的内容将与列表实现的序列化形式绑定在一起,因此在以后的Java版本中将其读回List可能会产生奇怪的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.