'Read all data from socket
I want read all data ,synchronously , receive from client or server without readline() method in java(like readall() in c++).
I don't want use something like code below:
BufferedReader reader = new BufferedReader(new inputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
document.append(line + "\n");
What method should i use?
Solution 1:[1]
If you know the size of incoming data you could use a method like :
public int read(char cbuf[], int off, int len) throws IOException;
where cbuf is Destination buffer.
Otherwise, you'll have to read lines or read bytes. Streams aren't aware of the size of incoming data. The can only sequentially read until end is reached (read method returns -1)
refer here streams doc
sth like that:
public static String readAll(Socket socket) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line).append("\n");
return sb.toString();
}
Solution 2:[2]
You could use something like this:
public static String readToEnd(InputStream in) throws IOException {
byte[] b = new byte[1024];
int n;
StringBuilder sb = new StringBuilder();
while ((n = in.read(b)) >= 0) {
sb.append(b);
}
return sb.toString();
}
Solution 3:[3]
try this
public static String readToEnd(InputStream in) throws IOException {
return new String(in.readAllBytes(),StandardCharsets.UTF_8);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | BQuadra |
| Solution 3 | The Mix-Ray |
