首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将ArrayList<String>转换为byte[]

将ArrayList<String>转换为byte[]
EN

Stack Overflow用户
提问于 2019-02-12 15:46:12
回答 6查看 3.7K关注 0票数 2

我希望能够转换存储从BufferedReader读取的文件内容的ArrayList<String>,然后将内容转换为byte[],以便使用Java类对其进行加密。

我尝试过使用.getBytes(),但它不起作用,因为我认为我需要首先转换ArrayList,而我在弄清楚如何做到这一点时遇到了麻烦。

代码:

代码语言:javascript
运行
复制
// 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));
    }

非常感谢,提前!

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2019-02-12 15:51:12

连接字符串或创建StringBuffer

代码语言:javascript
运行
复制
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();
票数 6
EN

Stack Overflow用户

发布于 2019-02-12 15:58:22

为什么你要把它读成字符串,然后把它转换成字节数组呢?从Java 7开始,您可以执行以下操作:

代码语言:javascript
运行
复制
byte[] input= Files.readAllBytes(new File(userFile.toPath());

然后将该内容传递给Cipher。

代码语言:javascript
运行
复制
byte[] output = cipher.doFinal(input);

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

票数 6
EN

Stack Overflow用户

发布于 2019-02-12 15:48:18

因此,完整的ArrayList实际上是一个单独的String

一种简单的方法是将其中的所有Strings合并为一个,然后对其调用.getBytes()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54645112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档