1

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.

Mx1co
  • 9
  • 1
  • 6
  • The code doesn't compile, because you have a typo in method return type (Sting instead of String). See [How to convert the DataInputStream to the String in Java?](https://stackoverflow.com/questions/3870847/how-to-convert-the-datainputstream-to-the-string-in-java) for an answer. – pafau k. May 21 '20 at 20:49
  • I´m sorry! That was a mistake of mine, but it wasn´t the reason why it doesnt compile. The line, which I made a comment on is the error – Mx1co May 21 '20 at 20:54

1 Answers1

0

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

ZINE Mahmoud
  • 1,272
  • 1
  • 17
  • 32