0

I'm trying to convert a byte array to a String and writing it to a file using PrintWriter (only to check it's value with mc, i need the content in String) My problem summed up:

//-77 is "equivalent" to 179 or 0xb3 (i also tried those using ByteArrayOutputStream, where these are valid values)
byte[] b = new byte[]{0,0,1,-77};

//I save the String to a txt, so i can check its value with midnight commander
try(  PrintWriter out = new PrintWriter("~/Desktop/output.txt")){
    out.println( new String(b) );
}

The output.txt's content as hex with mc: 00 00 01 EF | BF BD 0A
Despite it should be: 00 00 01 B3

What causes this? I guess it's the encoding, but I don't know what type of encoding should I use (i tried some Cp### types, but none of them works so far).

UPDATE:
Every negative byte converted to String like this will result: EF BF BD
So it only works if the unsigned byte value is less than 128. So the question is how can i represent a byte greater than 127 in String like i did with 0-127 bytes?

9
  • 2
    You should probably encode the bytes, as opposed to trying to use them as if they were a string. You should only use new String(byte[]) when the byte array is a valid encoding of a string. Commented Jun 14, 2017 at 11:08
  • HTTP can handle bytes. Commented Jun 14, 2017 at 11:09
  • Perhaps your byte array is signed. Try using unisgned byte[]. Commented Jun 14, 2017 at 11:20
  • Which encoding are your four input bytes in? If you can't answer that question, then String is not the right data type for you to use Commented Jun 14, 2017 at 11:43
  • Java doesn't have unsigned byte. I cannot just post a byte array, it needs to be a String. The shown code above is an example, but i need to send exact given bytes (as a String) so i cannot encode it. I have been using this type of conversion for circa 2 weeks and it works as it should be most of the time. This 0xb3 is the only value (so far) which causes the problem. Commented Jun 14, 2017 at 11:45

1 Answer 1

2

This will do the trick. It will output 00 00 01 b3 as expected.

FileOutputStream fos = new FileOutputStream("filename");
fos.write(b);
fos.close();
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the quick answer, it really did the trick. But writing it to a txt is just for testing purposes, i need its value as a String. Is there something similar to FileOutputStream for String? Or should i just read back the txt-s content? (That doesn't seem too optimal)
@leviathan11 That is a brand new question. Nobody will ever see it as a comment to an answer to a different question.
That was exactly my original question, but as this is my very fist post on stackoverflow i couldn't really compose it, so it got edited mispointing the topic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.