Upon running following code under class FlightSearch
String moreSearch = \"y\";
List resultList;
// load initial flight d
The problem is that you execute the br.close()
that, as javadoc states, closes the stream and releases any system resources associated with it.
Just for a quick verification comment out the:
if (br != null) {
// try {
// br.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
and you can answer s
any times you want without any exception.
A solution is closing the buffer reader after all reads are terminated:
String moreSearch = null;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {
do {
// ...
System.out.println("More Flight Query ? Press n/N to exit. Anyother key to continue searching.");
moreSearch = br.readLine();
} while (!moreSearch.equalsIgnoreCase("n"));
} catch (IOException e) {
Logger.getLogger(FlightSearch.class.getName()).log(Level.SEVERE, "Cant read line from a System.in based BufferedReader", e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignoreMe) {
Logger.getLogger(FlightSearch.class.getName()).log(Level.SEVERE, "Can't close a System.in based BufferedReader", ignoreMe);
}
}
}
After making changes as suggested in previous answer my code didn't tun but with slight more changes as shown below, my code compiled and run just fine
try {
do {
// main thread gets input
Input inputQuery = new Input();
inputQuery.getQuery();
// main thread STARTs processing task as background monitors csv
// repo
QueryProcessor processor = new QueryProcessor();
resultList = null;
resultList = processor.matchQuery(inputQuery);
displayResult(resultList, inputQuery.getFlightClass());
System.out
.println("More Flight Query ? Press n/N to exit. Anyother key to continue searching.");
moreSearch = br.readLine();
} while (!moreSearch.equalsIgnoreCase("n"));
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidException e1) {
e1.getMessage();
} finally {
fl.stopThread();
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Thank You !!!");
}
thanks for help.
Your issue is that you're calling br.close()
in the finally
block where you read a line from the buffer. When you close a Stream
, any stream that was wrapped by the one you closed is also closed. As a result, your first iteration through the do { } while ()
loop is closing the System.in InputStream
, which you cannot then reopen.
To avoid this, you can use a CloseShieldInputStream
from Apache Commons to wrap System.in
before you wrap it with the InputStreamReader
. This will allow you to close the BufferedReader
(which will also close the InputStreamReader
and the CloseShieldInputStream
) without triggering the closure of System.in
.
See bmargulies answer here: Closing BufferedReader and System.in