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
read(byte[] b, int off, int len) method reads len bytes from byte-input stream into a byte array, starting at a given offset. This method repeatedly invokes the read() method of the underlying stream.
To read a line of chars from console with an InputStream one should perform the following steps: Use System.in to get the standard InputStream. Create a new BufferedReader with a new InputStreamReader with the specified InputStream. Use readLine() API method of BufferedReader to read a line of text.
The BufferedInputStream maintains an internal buffer of 8192 bytes. During the read operation in BufferedInputStream , a chunk of bytes is read from the disk and stored in the internal buffer. And from the internal buffer bytes are read individually. Hence, the number of communication to the disk is reduced.
A BufferedInputStream reads from another InputStream , but a FileInputStream reads from a file1.
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);
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