简体   繁体   English

从文件读取时获得与写入文件不同的字节数组

[英]Getting different byte array than written to file when reading from file

I'm writing my byte array to a file: 我正在将字节数组写入文件:

PrintWriter pw = new PrintWriter(new FileOutputStream(fileOutput, true));
pw.write(new String(cryptogram, Charset.defaultCharset()));
pw.close();

Then, I am reading it from the file like this: 然后,我从这样的文件中读取它:

String cryptogramString = new String();
while (scPriv.hasNext()) {
    linePriv = scPriv.nextLine();
    cryptogramString += linePriv;
}

But I don't know how to make byte[] from cryptogramString . 但是我不知道如何从cryptogramString制作byte[] I'am trying this: 我正在尝试:

byte[] b = cryptogramString.getBytes(Charset.defaultCharset());
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(cryptogram));

But it doesn't return the same values. 但是它不会返回相同的值。 Does anyone have an idea how to make this right? 有谁知道如何解决这个问题?

You should decide whether you are writing text or binary. 您应该决定要编写文本还是二进制文件。

Encrypted data is always binary which means you shouldn't be using Reader/Writer/String classes. 加密的数据始终是二进制的,这意味着您不应该使用Reader / Writer / String类。

try (FileOutputstream out = new FileOutputStream(filename)) {
    out.write(bytes);
}

to read back in 读回

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 我有一个文件,其中包含xml,然后包含纯文本,因此我无法整体读取文件

You also can't write binary into a text file. 您也不能将二进制文件写入文本文件。 You can encode it using base64. 您可以使用base64对其进行编码。

Storing base64 data in XML? 以XML存储base64数据?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM