I use InputStream to read some data, so I want to read characters until new line or '\n'.
Depending on where the InputStream is coming from, you might not be able to reset it. You can check if mark() and reset() are supported using markSupported() . If it is, you can call reset() on the InputStream to return to the beginning. If not, you need to read the InputStream from the source again.
Use BufferedReader within the try-with block, which will close the resource after finishing with it. It is possible to read the input stream with BufferedReader and with Scanner.
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset . The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .
You should use BufferedReader
with FileInputStreamReader
if your read from a file
BufferedReader reader = new BufferedReader(new FileInputStreamReader(pathToFile));
or with InputStreamReader
if you read from any other InputStream
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Then use its readLine() method in a loop
while(reader.ready()) { String line = reader.readLine(); }
But if you really love InputStream then you can use a loop like this
InputStream stream; char c; String s = ""; do { c = stream.read(); if (c == '\n') break; s += c + ""; } while (c != -1);
BufferedReader
within the try-with
block, which will close the resource after finishing with it.It is possible to read the input stream with BufferedReader and with Scanner. If you don't have a good reason, it is better to use BufferedRead (for broad discussion BufferedReader vs Scanner see).
I would also suggest using the Buffered Reader with try-with-resources to make sure the resource are auto-closed. see
See the following code
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { while (reader.ready()) { String line = reader.readLine(); System.out.println(line); } }catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With