Osc*_*Ryz 33 java validation command-line double-click
我想要在控制台中显示一条消息或者弹出一个消息,所以如果没有指定参数,我想知道我应该显示哪个
就像是:
if( !file.exists() ) {
if( fromCommandLine()){
System.out.println("File doesn't exists");
}else if ( fromDoubleClickOnJar() ) {
JOptionPane.showMessage(null, "File doesn't exists");
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 18
直截了当的答案是,您无法分辨JVM是如何启动的.
但是对于您的问题中的示例用例,您实际上并不需要知道JVM是如何启动的.您真正需要知道的是用户是否会看到写入控制台的消息.这样做的方法是这样的:
if (!file.exists()) {
Console console = System.console();
if (console != null) {
console.format("File doesn't exists%n");
} else if (!GraphicsEnvironment.isHeadless()) {
JOptionPane.showMessage(null, "File doesn't exists");
} else {
// Put it in the log
}
}
Run Code Online (Sandbox Code Playgroud)
控制台的javadoc 虽然不防水,但强烈暗示Console对象(如果存在)写入控制台并且无法重定向.
谢谢@Stephen Denne的!GraphicsEnvironment.isHeadless()提示.