Closing BufferedReader and System.in
Asked Answered
L

2

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?

Legislatorial answered 20/11, 2011 at 19:16 Comment(4)
delete what file? BufferedReaders are meant to be bound to particular input stream. Once you close them you cannot reuse them.Rubric
You really shouldn't need to close br in order to delete a file.Kinnard
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.Lohrman
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.Legislatorial
C
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.

Clemons answered 20/11, 2011 at 19:28 Comment(2)
You say 'new CloseShieldInputStream(System.in)'Clemons
thank you. I ended up using a way around this, I didn't delete that file, I just re-wrote it with the correct information :)Legislatorial
H
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.

Haler answered 4/12, 2014 at 0:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.