3

I'm required due to previous implementation to use an InputStream, I can't use a BufferedReader.

My test bench used a BufferedReader and a while loop, like so:

while ((line = br.readLine()) != null)

However br is now required to be an InputStream (and will be renamed). Is there any way of reading in this fashion with an InputStream, or do I have to read it bytes at a time and search for the \n?

Brydon Gibson
  • 1,179
  • 3
  • 11
  • 22

2 Answers2

7

If you must read with an InputStream, then wrap it into a InputStreamReader, and then wrap this in a BufferedReader, allowing you to use your familiar BufferedReader methods. There's no need to do non-buffered input in this situation.

// assuming that you have an InputStream named inputStream
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
    String line = null;
    while((line = br.readLine()) != null) {
        // use line here
    }
} catch (IOException e) {
    e.printStackTrace();
}

Or alternatively, wrap the InputStream in a Scanner object:

try (Scanner scanner = new Scanner(inputStream)) {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        // use line here
    }
} 
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

You can change the code like this :

    public String readLine(InputStream inputStream) throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int r;

        for (r = inputStream.read(); r != '\n' && r != -1 ; r = inputStream.read()) {
            baos.write(r);
         }

        if (r == -1 && baos.size() == 0) {
           return null;
         }

        String lines = baos.toString("UTF-8");
        return lines;
        }

Maybe this example helps you..

Coder ACJHP
  • 1,940
  • 1
  • 20
  • 34