为了账号安全,请及时绑定邮箱和手机立即绑定

将 ArrayList<String> 转换为 byte[]

将 ArrayList<String> 转换为 byte[]

梦里花落0921 2022-06-15 14:44:53
我希望能够转换一个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();


查看完整回答
反对 回复 2022-06-15
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

为什么要将其读取为字符串并将其转换为字节数组?从 Java 7 开始,您可以执行以下操作:

byte[] input= Files.readAllBytes(new File(userFile.toPath());

然后将该内容传递给密码。

byte[] output = cipher.doFinal(input);

您也可以考虑使用流(InputStream 和 CipherOutputStream)而不是将整个文件加载到内存中,以防您需要处理大文件。


查看完整回答
反对 回复 2022-06-15
?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

那么,fullArrayList实际上是 singleString吗?

一种直接的方法是将其中的所有Strings内容合并为一个,然后调用.getBytes()它。


查看完整回答
反对 回复 2022-06-15
  • 3 回答
  • 0 关注
  • 274 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号