6
Reader rdr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(rdr);
String s;
s = br.readLine();
br.close();
Scanner sc = new Scanner(System.in);
s = sc.nextLine();
System.out.print(s);

I've noticed that if I close the BufferedReader, I won't be able to insert input from the keyboard anymore, as System.in is somehow closed. Is there anyway I can keep br.close() (I need that in order to delete a file) and then add more input from the keyboard?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Bogdan Tomi
  • 129
  • 2
  • 12
  • 2
    delete what file? BufferedReaders are meant to be bound to particular input stream. Once you close them you cannot reuse them. – soulcheck Nov 20 '11 at 19:24
  • 7
    You *really* shouldn't need to close `br` in order to delete a file. – Jon Skeet Nov 20 '11 at 19:26
  • 2
    If you are reading from a file, and using a `BufferedReader` upto some point and, then close the `BufferedReader` and then read more from the file stream, you will miss some bytes. These bytes are consumed by the buffered reader (in order to buffer). You'll need to find another way. Why do you need to go from a Reader subclass to a Scanner? Some api restrictions? In either case, you can do things differently, for example by using a `RandomAccessFile` and/or a custom Scanner subclass that can do Reader things too. – Mark Jeronimus Nov 20 '11 at 19:40
  • It's a file I'm reading with the BufferedReader. Then I need to delete it. And I can't delete the file (file.delete() returns false) if I don't close the BufferedReader. – Bogdan Tomi Nov 20 '11 at 22:33

2 Answers2

2

Looks like you need:

http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CloseShieldInputStream.html

Wrap that around System.in before making your reader, and then all will be well, since you won't do that when you are using a FileInputStream.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
0

If you just want to get input from keyboard by System.in, please use static BufferedReader wrapping InputStreamReader (also wrapping System.in). Like this:

 Public BufferedReader is = new BufferedReader(new InputStreamReader(System.in));

And is.close(); would be needed right before your application terminated.

Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32
kindlee
  • 11