问题
I have an InputStream which contains a line as a string and then binary data.
If I read the line using new BufferedReader(new InputStreamReader(inputStream))
, the binary data is being also read and cannot be re-read.
How can I read a line without reading the binary data as well?
回答1:
* Update: It seems that InputStreamReader buffers (reads ahead) as well :( Posted another answer to directly read from the InputStream.
Eventually did it manually :(
I guess I missed a lot of cases like \r and white spaces.
public static String readLine(InputStream inputStream) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
StringBuilder stringBuilder = new StringBuilder();
int c;
for (c = reader.read(); c != '\n' && c != -1 ; c = reader.read()) {
stringBuilder.append((char)c);
}
if (c == -1 && stringBuilder.length() == 0) return null; // End of stream and nothing to return
return stringBuilder.toString();
}
回答2:
Eventually did it manually directly reading byte after byte from the InputStream without wrapping the InputStream. Everything I tried, like Scanner and InputStreamReader, reads ahead (buffers) the input :(
I guess I missed a some cases like \r.
public static String readLine(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int c;
for (c = inputStream.read(); c != '\n' && c != -1 ; c = inputStream.read()) {
byteArrayOutputStream.write(c);
}
if (c == -1 && byteArrayOutputStream.size() == 0) {
return null;
}
String line = byteArrayOutputStream.toString("UTF-8");
return line;
}
回答3:
Have you tried DataInputStream ?
回答4:
You Could try Scanner Class.... (java.util.Scanner;)
Scanner in = new Scanner(System.in);
String Str = in.nextLine();
来源:https://stackoverflow.com/questions/25215564/how-to-read-a-line-from-inputstream-without-buffering-the-input