0

I have to work with byte array and string in java . I read a file using java and and get the byte code from getBytes() method which is [B@1d1cdf7]

Is this possible to work again with this code . In my program to decode back to java string. I need byte array so how can i store this value in byte array. I want something like in another program i dont have the original text and i have only the byte array then how can i get back the string result.

Pratik Shelar
  • 3,154
  • 7
  • 31
  • 51
adesh singh
  • 1,727
  • 9
  • 38
  • 70

4 Answers4

0

You can use something like this:

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    while(/* condition */ ) { // Get bytes from the file
        // Append bytes to the byteArray
        stream.write(bytes); 
    }

    String str = new String(stream.toByteArray()); // Get the string representation
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

You need to convert getBytes() to String.

public String toString(){
   return new String(getBytes());
}
user2927772
  • 53
  • 1
  • 6
0

To convert string to byte array try this

String test = "This is a test";

byte[] bytes = test.getBytes();
System.out.println("Byte : " + bytes);

now to convert byte array to string try this

String s = new String(bytes);
System.out.println("Text : " + s);

output

Byte : [B@25154f

Text : This is a test
Vijay Vankhede
  • 3,018
  • 1
  • 26
  • 46
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
-1

You can use Base64 encoding. This encoding is more suitable and portable for save binary data into string.

Base64 api in java :

sun.misc.BASE64Encoder;
sun.misc.BASE64Decoder;
Vahid
  • 137
  • 8