Writing byte array to txt-file and reading it back

2019-08-06 00:48发布

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.

2条回答
2楼-- · 2019-08-06 01:25

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 do String line = new String(Arrays.toString(name_of_array))

public class StringToByteArray {
public static void main(String args[])
{
    String line= "[-3, 123, 89, 0, -34, 78, -45, -78]";
    String some=line.substring(1, line.length()-1);     
    int element_counter=1;

    for(int i=0; i<some.length(); i++)
    {           
        if (some.substring(i, i+1).equals(","))
        {
            element_counter++;
        }       

    }
    int [] comas =new int[element_counter-1];
    byte [] a=new byte[element_counter];
    if (a.length==1)
    {
        a[0]= Byte.parseByte(some.substring(0));
    }       
    else 
    {
        int j=0;
        for (int i = 0; i < some.length(); i++) 
        {
            if (some.substring(i, i+1).equals(","))
            {
                comas[j]=i;
                j++;
            }
        }           
        for (int i=0; i<element_counter; i++)
        {
            if(i==0)
            {
                a[i]=Byte.parseByte(some.substring(0, comas[i]));
            }
            else if (i==element_counter-1)
            {
                a[i]=Byte.parseByte(some.substring(comas[comas.length-1]+2));
            }
            else
            {
                a[i]=Byte.parseByte(some.substring(comas[i-1]+2, comas[i]));
            }

        }
    }
    System.out.println(a[0]);

}
}

Result -3

I Hope it will be helpful

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-06 01:49

For me, this preserves the negative value:

package com.sandbox;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;

public class Sandbox {

    public static void main(String args[]) throws UnsupportedEncodingException {
        byte[] a = new byte[2];
        a[0] = 15;
        a[1] = -2;
        String line = new String(a);
        byte[] b = line.getBytes();
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
        System.out.println(Charset.defaultCharset());
    }        
}

For me, this outputs:

[15, -2]
[15, -2]
windows-1250

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 start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

If you really must use a String to hold binary data then the safest way is to use Base64 encoding.

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.

查看更多
登录 后发表回答