Java Dailly Tips - Read Line With File Using Inputstream

Java Dailly Tips - Read Line With File Using Inputstream

Problem

I use InputStream to read some data, so I want to read characters until new line or '\n'.

Solution

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

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. I would also suggest using the Buffered Reader with try-with-resources to make sure the resource are auto-closed. see

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

Share this Post