我引用了 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();
}
我的问题是如何将数组中的加密字符串写入文件。有什么指点吗?
最佳答案
您只是将数组的字符串值写入文件(因为您使用了 Array.toString(str))。这通常只是引用的某种表示。您必须连接数组的值或遍历它并单独加密/写入每个值。
此外,您不应使用 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。
关于java - 将字符串数组中的加密字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30351926/