Java DataInputStream convert to byte array?

Mx1co :

I´ve got a DataInputStream and I have a method, which should return a String. I know, that my Datastream receives a packet, containing a String. But my code, which I´ve written doesn´t compile. I´m using TCP- sockets and streams to send / receive data. It is important to say, that I must use Java 1.8 compiler! Thats the reason, why I cant use in.readAllBytes()

public String readString(DataInputStream in) throws IOException {
String str;
byte[] bytes = in. //dont know what to write here
str = bytes.toString();
return str;
}

So, as you can see I first create a new ByteArray variable. After this, the byteArray should convert to a String.

ZINE Mahmoud :

short answer :

byte[] bytes = new byte[in.available()];

or

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[1024];
    while ((nRead = in.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    buffer.flush();
    byte[] bytes= buffer.toByteArray();

Long answer :

in case of fixed size stream

InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
byte[] targetArray = new byte[initialStream.available()];

in case if you don't know the exact size of the underlying data

InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); // not really unknown
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
    buffer.write(data, 0, nRead);
}

buffer.flush();
byte[] byteArray = buffer.toByteArray();

starting with java 9 you can use this :

InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
byte[] data = is.readAllBytes();

usefull ressources : you can find more others alternatives to do this here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related