Szymon Kaczorowski Szymon Kaczorowski - 7 months ago 11
Java Question

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
. 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?

Answer

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.

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

You also can't write binary into a text file. You can encode it using base64.

Storing base64 data in XML?