I have an unusual problem with BufferedReader in Java 11. I have a simple command-line student tracker application, that reads input from System.in
, transforms it into the appropriate implementation of Command
interface, and executes it.
void execute() {
System.out.println("Learning Progress Tracker");
try (reader) { // reader is new BufferedReader(new InputStreamReader(System.in))
String line;
while (!shutdown) {
line = reader.readLine();
Command command = Command.stringToCommand(line);
if (command instanceof ExitCommand) {
shutdown = true;
}
command.execute(reader, db);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Some commands simply process the input and print the output to System.out
, some keep using reader
to receive additional input. For example, AddStudentsCommand
implements execution like so:
public void execute(BufferedReader reader, Database db) {
String line;
String[] credentials;
int numAdded = 0;
prompt(); // Prints prompt to System.in to enter credentials
try {
while (!(line = reader.readLine()).equals("back")) {
// process input
}
}
}
Here is the weird part. After while (!(line = reader.readLine()).equals("back")) {
line evaluates to true, reader
's buffer ends up with leading \n
in its buffer, followed by whatever I typed, which causes to readLine()
to fire up twice. And even weirder, that only happens if I comment out prompt()
(a simple System.out.println()
) prior to readLine()
. If some text gets printed to System.out
before reading, the buffer behaves correctly and leading \n
doesn't show up. I have recorded a small video to show what I mean: https://www.youtube.com/watch?v=H7PBr6Qpykg.
I don't know what I'm doing wrong and can't understand where that nasty bug is coming from. Can anyone reproduce?
CodePudding user response:
This issue only occurs when you run your program in the IDE. If you run it from the command line, using the command java [ClassName]
, it should work just fine.
The problem is a bug in IntelliJ IDEA which was fixed in version 2022.1.2, so you might want to upgrade.