猿问

将 ArrayList<String> 转换为 byte[]

我希望能够转换一个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));

    }

提前谢谢了!


梦里花落0921
浏览 275回答 3
3回答

MYYA

连接字符串,或创建一个StringBuffer.StringBuffer buffer = new StringBuffer();String line;String userFile = file + ".txt";BufferedReader in = new BufferedReader(new FileReader(userFile));while ((line = in.readLine()) != null) {&nbsp; &nbsp;buffer.append(line); //error here}byte[] bytes = buffer.toString().getBytes();

慕哥9229398

为什么要将其读取为字符串并将其转换为字节数组?从 Java 7 开始,您可以执行以下操作:byte[]&nbsp;input=&nbsp;Files.readAllBytes(new&nbsp;File(userFile.toPath());然后将该内容传递给密码。byte[]&nbsp;output&nbsp;=&nbsp;cipher.doFinal(input);您也可以考虑使用流(InputStream 和 CipherOutputStream)而不是将整个文件加载到内存中,以防您需要处理大文件。

一只名叫tom的猫

那么,fullArrayList实际上是 singleString吗?一种直接的方法是将其中的所有Strings内容合并为一个,然后调用.getBytes()它。
随时随地看视频慕课网APP

相关分类

Java
我要回答