0

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?

Jeff B
  • 8,572
  • 17
  • 61
  • 140
Pan Wolodyjowsky
  • 388
  • 6
  • 26
  • I don't understand _doesn't return me same values_. What are you comparing? – Savior Apr 26 '16 at 18:21
  • 3
    This doesn't actually sound like something that should be interacting with strings, but rather should be just using `InputStream` and `OutputStream` and dealing strictly with bytes? – Louis Wasserman Apr 26 '16 at 18:22
  • System.out.println(Arrays.toString(b)); is not the same as System.out.println(Arrays.toString(cryptogram)); – Pan Wolodyjowsky Apr 26 '16 at 18:22
  • I have a file that contains xml and then plain text, so i cant read a file as a whole – Pan Wolodyjowsky Apr 26 '16 at 18:23
  • `hasNext` checks for an available token, while `nextLine` reads until the next line separator, excluding the line separator characters from the return value. Just read the file into a `byte[]` directly as previously suggested. – Savior Apr 26 '16 at 18:25

1 Answers1

2

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?

Community
  • 1
  • 1
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130