Szymon Kaczorowski Szymon Kaczorowski - 9 months ago 18
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()));

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
. I'am trying this:

byte[] b = cryptogramString.getBytes(Charset.defaultCharset());

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.

try (FileOutputstream out = new FileOutputStream(filename)) {

to read back in

byte[] bytes = new byte[(int) (new File(filename).length())];
try (FileInputstream in = new FileInputStream(filename)) {;

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?