如何在不缓冲输入的情况下从InputStream中读取一行?

我有一个InputStream,它包含一行作为字符串,然后是二进制数据。

如果我使用new BufferedReader(new InputStreamReader(inputStream))读取该行,则也会读取二进制数据并且无法重新读取。

如何在不读取二进制数据的情况下读取一行?

最终手动完成:(

我想我错过了很多像\ r和白色空格的情况。

 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(); } 

最终手动直接从InputStream读取字节,而不包装InputStream。 我尝试过的所有东西,比如Scanner和InputStreamReader,都会向前读取(缓冲区)输入:(

我想我错过了一些像\ r \ n的案例。

 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; } 

你试过DataInputStream吗?

你可以试试Scanner Class ….(java.util.Scanner;)

Scanner in = new Scanner(System.in);

String Str = in.nextLine();