Java 转换ArrayList<;字符串>;到字节[]

Java 转换ArrayList<;字符串>;到字节[],java,string,encryption,arraylist,byte,Java,String,Encryption,Arraylist,Byte,我希望能够转换存储从BufferedReader读取的文件内容的ArrayList,然后将内容转换为字节[],以允许使用Java的密码类对其进行加密 我尝试过使用.getBytes(),但它不起作用,因为我认为我需要先转换ArrayList,而我很难弄清楚如何进行转换 代码: //文件变量 私有静态字符串文件; //来自main() file=args[2]; 私有静态void sendData(SecretKey desedeKey、DataOutputStream dos)引发异常{ Arr

我希望能够转换存储从BufferedReader读取的文件内容的
ArrayList
,然后将内容转换为字节[],以允许使用Java的密码类对其进行加密

我尝试过使用
.getBytes()
,但它不起作用,因为我认为我需要先转换ArrayList,而我很难弄清楚如何进行转换

代码:

//文件变量
私有静态字符串文件;
//来自main()
file=args[2];
私有静态void sendData(SecretKey desedeKey、DataOutputStream dos)引发异常{
ArrayList fileString=新的ArrayList();
弦线;
字符串userFile=file+“.txt”;
BufferedReader in=new BufferedReader(new FileReader(userFile));
而((line=in.readLine())!=null){
fileString.add(line.getBytes());//此处出错
}
Cipher Cipher=Cipher.getInstance(“DESede/ECB/PKCS5Padding”);
cipher.init(cipher.ENCRYPT_模式,desedeKey);
byte[]output=cipher.doFinal(fileString.getBytes(“UTF-8”);//此处出错
dos.writeInt(输出.长度);
写入(输出);
System.out.println(“加密数据:+Arrays.toString(输出));
}

非常感谢,提前

那么,完整的
数组列表
实际上是一个
字符串


一种简单的方法是将其中的所有
字符串合并为一个字符串,然后在其上调用
.getBytes()

为什么要使用ArrayList。只需使用StringBuffer并将文件的完整内容保存到单个字符串中。

将所有字符串合并到单个字符串中即可

String anyName = allstring;
然后叫这个

anyName.getBytes();

它将帮助您。

连接字符串或创建
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();

您可以尝试利用Java的序列化功能,并使用围绕字节输出流的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版本中,将其读回列表可能会产生奇怪的结果。

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

byte[] input= Files.readAllBytes(new File(userFile.toPath());
然后将该内容传递给密码

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

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

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