How to read a line in BufferedInputStream?
Asked Answered
F

2

24

I am writing a code to read Input from user by using BufferedInputStream, But as BufferedInputStream reads the bytes my program only read first byte and prints it. Is there any way I can read/store/print the whole input ( which will Integer ) besides just only reading first byte ?

import java.util.*;
import java.io.*;
class EnormousInputTest{

public static void main(String[] args)throws IOException {
        BufferedInputStream bf = new BufferedInputStream(System.in)   ;
    try{
            char c = (char)bf.read();

        System.out.println(c);
    }
finally{
        bf.close();
}   
}   
}

OutPut:

[shadow@localhost codechef]$ java EnormousInputTest 5452 5

Fred answered 17/10, 2014 at 6:58 Comment(2)
Why don't you use a BufferedReader instead?Brainwash
I have to process approx 2.5 MB/S , And as per CodeChef BufferedInputStream is the fastest one.Fred
P
38

A BufferedInputStream is used to read bytes. Reading a line involves reading characters.

You need a way to convert input bytes to characters which is defined by a charset. So you should use a Reader which converts bytes to characters and from which you can read characters. BufferedReader also has a readLine() method which reads a whole line, use that:

BufferedInputStream bf = new BufferedInputStream(System.in)

BufferedReader r = new BufferedReader(
        new InputStreamReader(bf, StandardCharsets.UTF_8));

String line = r.readLine();
System.out.println(line);
Patisserie answered 17/10, 2014 at 7:4 Comment(1)
+Long.MAX_VALUE for actually explaining why the OP needs a Reader. There are so many answers simply reading "use this instead: [pasted code]".Viminal
P
3

You can run this inside a while loop.

Try below code

BufferedInputStream bf = new BufferedInputStream(System.in)   ;
    try{
        int i;
        while((i = bf.read()) != -1) {
            char c = (char) i;
            System.out.println(c);
        }
    }
    finally{
        bf.close();
    }
}

But keep in mind this solution is inefficient than using BufferedReader since InputStream.read() make a system call for each character read

Picul answered 17/10, 2014 at 7:16 Comment(3)
If it's so bad, it doesn't probably belong at a site that's supposed to teach good practices :^)Electrify
There are times when the input stream never finishes a line (has no end of line character). In this case, reading character by character might be the only way to proceed.Ocieock
Fine for my case: Had to compute some commands from socket as strings and the rest as a file. perfect solution!Estrous

© 2022 - 2024 — McMap. All rights reserved.