I am trying to read lines of text from the console. The number of lines is not known in advance. The BufferedReader.readLine() method reads a line but after the last line it waits for input from the console. What should be done in order to avoid this?
Please see the code snippet below:
public static String[] getLinesFromConsole() {
String strLine = "";
try {
// Get the object of DataInputStream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null)
strLine += line + "~"; //edited
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return strLine.split("~");
}
The below code might fix, replace text exit
with your requirement specific string
public static String[] getLinesFromConsole() {
String strLine = "";
try {
// Get the object of DataInputStream
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null && !line.equals("exit") )
strLine += br.readLine() + "~";
isr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return strLine.split("~");
}