将字符串数组中的加密字符串写入文件

Writing encrypted strings from a string array into a file

参考了this question,设置加密成功。但是,我试图在一串数组上使用这种加密来写入文件。这就是我设置方法的方式,但我最终只将一个字符串数组写入文件。

String[] str = new String ["X: Adam", "Y: Barry", "z: Oliver"];

File file = new File(Path + "/EncryptedFile.txt);

调用方法将字符串数组写入文件:Crypto.WriteEncrypteFile(str, file);

方法

Public void WriteEncrypteFile(String[] str, File file) {
  try { 
    BufferedWriter w = new BufferedWriter(new FileWriter(file)); 
    byte[] tmptxt = Array.toString(str).getbytes(Charset.forName(" UTF-8 "));  
    byte[] encTxt = cipher.doFinal(tmptxt);
    w.write(string.valueOf(encTxt)); 
    w.flush();
    w.close(); 
  } catch (Exception e){
    e.printStackTrace();
  }    

我的问题是如何将数组中的加密字符串写入文件。有什么指点吗?

您可以使用Arrays.toString(),但这样您需要解析它才能阅读。或者,您也可以使用 OutputStream 直接在文件中写入 byte[]。除非您希望人类(例如您自己)阅读它,否则无需转换为字符串。

您只是将数组的字符串值写入文件(因为您使用了 Array.toString(str))。这通常只是参考的某种表示。您必须连接数组的值或遍历它并 encrypt/write 每个值单独。

此外,您不应使用 Writer 编写不包含字符的内容。作者总是尝试对输出进行编码,这可能会破坏您精心设置的字节。

只需使用 FileOutputStream 并用它写入字节:

try( FileOutputStream fos = new FileOutputStream(file) ) {
    for(String s : str) {
        byte[] tmptxt = s.getbytes(Charset.forName("UTF-8"));  
        byte[] encTxt = cipher.doFinal(tmptxt);
        w.write(encTxt);
    }
} catch(IOException e) {
    // print error or whatever
}

对于阅读,您执行相同的操作,但使用的是 FileInputStream。