从文件读取时获取与写入文件不同的字节数组
Getting different byte array than written to file when reading from file
我正在将字节数组写入文件:
PrintWriter pw = new PrintWriter(new FileOutputStream(fileOutput, true));
pw.write(new String(cryptogram, Charset.defaultCharset()));
pw.close();
然后,我像这样从文件中读取它:
String cryptogramString = new String();
while (scPriv.hasNext()) {
linePriv = scPriv.nextLine();
cryptogramString += linePriv;
}
但我不知道如何从 cryptogramString
制作 byte[]
。我正在尝试这个:
byte[] b = cryptogramString.getBytes(Charset.defaultCharset());
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(cryptogram));
但它 return 的值不同。有谁知道如何解决这个问题?
您应该决定是编写文本还是二进制文件。
加密数据始终是二进制的,这意味着您不应该使用 Reader/Writer/String 类.
try (FileOutputstream out = new FileOutputStream(filename)) {
out.write(bytes);
}
回读
byte[] bytes = new byte[(int) (new File(filename).length())];
try (FileInputstream in = new FileInputStream(filename)) {
in.read(bytes);
}
I have a file that contains xml and then plain text, so i cant read a file as a whole
您也不能将二进制文件写入文本文件。您可以使用 base64 对其进行编码。
Storing base64 data in XML?
我正在将字节数组写入文件:
PrintWriter pw = new PrintWriter(new FileOutputStream(fileOutput, true));
pw.write(new String(cryptogram, Charset.defaultCharset()));
pw.close();
然后,我像这样从文件中读取它:
String cryptogramString = new String();
while (scPriv.hasNext()) {
linePriv = scPriv.nextLine();
cryptogramString += linePriv;
}
但我不知道如何从 cryptogramString
制作 byte[]
。我正在尝试这个:
byte[] b = cryptogramString.getBytes(Charset.defaultCharset());
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(cryptogram));
但它 return 的值不同。有谁知道如何解决这个问题?
您应该决定是编写文本还是二进制文件。
加密数据始终是二进制的,这意味着您不应该使用 Reader/Writer/String 类.
try (FileOutputstream out = new FileOutputStream(filename)) {
out.write(bytes);
}
回读
byte[] bytes = new byte[(int) (new File(filename).length())];
try (FileInputstream in = new FileInputStream(filename)) {
in.read(bytes);
}
I have a file that contains xml and then plain text, so i cant read a file as a whole
您也不能将二进制文件写入文本文件。您可以使用 base64 对其进行编码。
Storing base64 data in XML?