0

I'm currently doing an assignment and I have a byte array that I write onto a file. I want to be able to get the byte array back out of the file by doing the reverse of what I did but I don't think I'm getting the right value back.

This is the code to write to the text file

PrintWriter fw = new PrintWriter(new BufferedWriter(new FileWriter("tc.txt",true)));
KeyPair keyPair = generateKeyPair();
byte[] publicKey = keyPair.getPublic().getEncoded();
byte[] privateKey = keyPair.getPrivate().getEncoded();
fw.println(email +" " + publicKey + " " + privateKey); //adds the site into the text file whcih contains all the blacklisted sites
fw.flush();

And I try to get information back as a string and use .getBytes() to convert it back to a byte array like this

tempPublicKey = (blScanner.next()).getBytes();

It doesn't seem to be right, does something happen in-between that is wrong?

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
mvantastic
  • 37
  • 2
  • 9
  • What input do you give and what output do you receive? – nhouser9 Apr 02 '17 at 17:40
  • 1
    That writes the toString() representation of each byte array (which does NOT containg the contents of the byte array) to the file. It's not a correct way to write bytes to a file. And there's no way you can read and get back the byte array contents. – JB Nizet Apr 02 '17 at 17:41

1 Answers1

0

As you are writing arbitrary byte sequence to a text file, consider encoding your bytes to base64 format upon writing and decoding when you read this text file.

Text files are not suitable to store and retrieve arbitrary byte sequences, because some bytes may be recognized as formatting characters, etc, etc.

Encoding your bytes to base64 and decoding it back will preserve your byte sequence upon writing and reading to/from text file.

Community
  • 1
  • 1