简体   繁体   English

将字节数组写入txt文件并读回

[英]Writing byte array to txt-file and reading it back

I have a byte array, that I need to write to txt-file. 我有一个字节数组,需要将其写入txt文件。 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. 我读了这个将Java字符串转换为字节数组的方法,但是它仅适用于正数。 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. toString()不能正常工作。

Thank you in advance for help. 预先感谢您的帮助。

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. 实际上,您尝试执行的操作中的缺陷是首先将字节放入String中。 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". ...如果您以byte []开头并且实际上不包含文本数据,则没有“正确转换”。 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. 字符串用于文本,byte []用于二进制数据,唯一真正明智的做法是避免在它们之间进行转换,除非绝对必要。

If you really must use a String to hold binary data then the safest way is to use Base64 encoding. 如果确实必须使用String来保存二进制数据,那么最安全的方法是使用Base64编码。

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. 有很多SO答案向您展示如何执行此操作。

I wrote my small function that converts String like [-3, 123, 89, 0, -34, 78, -45, -78] to byte array. 我写了一个小函数,将[-3, 123, 89, 0, -34, 78, -45, -78]这样的String转换为字节数组。 I didn't know how to use Base64 encoding. 我不知道如何使用Base64编码。 So I wrote my small function. 所以我写了我的小函数。 To get Above mentioned string we should do String line = new String(Arrays.toString(name_of_array)) 要获取上述字符串,我们应该执行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 结果-3

I Hope it will be helpful 希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM