I have a byte array, that I need to write to txt-file. After that I need to read that byte array from there and here appears a problem. I read this Convert Java string to byte array But it works only with positive numbers. Here what I have
public static void main(String args[]) throws UnsupportedEncodingException
{
byte [] a= new byte [2];
a[0]=15;
a[1]=-2;
String line = new String(a, "UTF-8");
byte[] b = line.getBytes();
System.out.println(b[0]);
System.out.println(b[1]);
}
and result is
15
63
toString()
doesn't work as well.
Thank you in advance for help.
I wrote my small function that converts String like
[-3, 123, 89, 0, -34, 78, -45, -78]
to byte array. I didn't know how to use Base64 encoding. So I wrote my small function. To get Above mentioned string we should doString line = new String(Arrays.toString(name_of_array))
Result
-3
I Hope it will be helpful
For me, this preserves the negative value:
For me, this outputs:
Basically, you're using the wrong charset to preserve negative bytes. You can find more info here. And actually, the flaw in what you're trying to do is put bytes into a String in the first place. As you can see here,
If you don't actually need to store this in a String, you should write/read from an Input/Output stream to the file. There are plenty of SO answers showing you how to do this.