问题
This is a follow-up question to this.
I asked this question yesterday, and although it is not resolved yet, I tried to make some silly changes to the code to just make it compile once (replacing console.format()
statements by System.out.print
statements, and adding null
as the second argument to the readLine()
methods).
Luckily the code did run, but it prints No console.
(obviously because the JVM
does not have a console device. Reference)
So how can I get the console device, supposed to be represented by an object of the Console class?
For convenience, I am adding the code after I made the aforementioned silly changes to it to make it run:-
import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/*
* Enter your regex: foo
* Enter input string to search: foo
* I found the text foo starting at index 0 and ending at index 3.
* */
public class RegexTestHarness {
public static void main(String[] args){
Console console = System.console();
if (console == null) {
System.err.println("No console.");
System.exit(1);
}
while (true) {
Pattern pattern =
Pattern.compile(console.readLine("%nEnter your regex: ", null));
Matcher matcher =
pattern.matcher(console.readLine("Enter input string to search: ", null));
boolean found = false;
while (matcher.find()) {
/*console.format("I found the text" +
" \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());*/
System.out.println("I found the text " + matcher.group() + " starting at index " + matcher.start() + " and ending at index " + matcher.end() + ".");
found = true;
}
if(!found){
//console.format("No match found.%n", null);
System.out.println("No match found.");
}
}
}
}
回答1:
Your application will only have a console device to open if it was started from a terminal and does not have stdin or stdout redirection. Basically the function isatty() would have to return true. Windows application typically do not have consoles if they are started from explorer. You should start them from the command prompt (cmd.exe).
来源:https://stackoverflow.com/questions/24236355/no-console-found-how-to-get-the-console-for-my-jvm