22

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

PankajKushwaha
  • 732
  • 1
  • 8
  • 21

2 Answers2

36

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);
icza
  • 289,344
  • 42
  • 658
  • 630
  • 4
    +`Long.MAX_VALUE` for actually explaining why the OP needs a `Reader`. There are so many answers simply reading "use this instead: [pasted code]". – Joffrey Oct 17 '14 at 07:11
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

sam_eera
  • 619
  • 4
  • 18
  • If it's so bad, it doesn't probably belong at a site that's supposed to teach _good_ practices :^) – ivan_pozdeev Oct 20 '14 at 17:24
  • 1
    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. – Dale Aug 25 '15 at 16:14
  • Fine for my case: Had to compute some commands from socket as strings and the rest as a file. perfect solution! – flyOWX Feb 09 '17 at 10:54