Kyranstar
Kyranstar

Reputation: 1720

Java byte[] to string conversion outputting byte

In my code, I am sending a txt file encoded into a byte array over the internet, and then converting the message back on the other side and displaying it. The problem is that when I try displaying it, it always comes out as "[B@1ef9f1d" or "[B@1764be1" etc.

This is what recieves the data

private void parsePacket(byte[] data, InetAddress address, int port) {
    String datasent[] = (new String(data).trim()).split(",");
    String type = datasent[0];
    String message = datasent[1];
    switch(type){//Data we are receiving from client, type is 5 char
    default:
        System.out.println(type);
        System.out.println(message);
    case "invalid":
        println("Invalid packet", new Color(255, 155, 155));
        break;
    case "login":
        addConnection(message, address, port);
        break;
    case "SendLog":
        printLog(message);
        break;
    }
}
private void printLog(String message) {
    int charperline = 10;
    String line ="";
    for (int i = 0; i < message.length() / charperline; i++){
        for (int j = 0; j < charperline; j++){
        line += message.charAt(i + j);
        }
        println("LOG: " + line);
        line = "";
    }

}

And this is what sends it:

public void sendLog(){
    System.out.println("sendlog()");
    InputStream is = getClass().getResourceAsStream("/LOG.txt");
    try
    {
        byte[] text = new byte[10000];
        is.read(text);
            sendData(("SendLog," + text).getBytes());
        //is.close();
        new File("/LOG.txt").delete();
    } catch (IOException e) {
        e.printStackTrace();
    } 
}
public void sendData(byte[] data){
    DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 1332);
    try {
        socket.send(packet);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e){
        e.printStackTrace();
    }
}

Upvotes: 0

Views: 363

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280172

What you are seeing

[B@1ef9f1d

is the result of the method toString() that all classes inherit from the Object class, since all classes in Java extend Object. This is implemented as

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

In this case, getClass().getName() would return [B because it is an array of Bytes.

This is because array objects in Java do not have a custom toString() method, they inherit Object's.

If you want to print the contents of an array, try

Arrays.toString(yourByteArray);

For custom classes, you should always implement (override) your own custom toString() method. It is useful for logging. Note that String concatenation when used with reference types uses the toString() method implicitly to convert your object into a String representation.

Upvotes: 3

Related Questions