有没有办法知道一个Java程序是从命令行还是从一个jar文件启动? [英] Is there a way to know if a Java program was started from the command line or from a jar file?

查看:86
本文介绍了有没有办法知道一个Java程序是从命令行还是从一个jar文件启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在控制台中显示一条消息,或者弹出一个消息,所以如果没有指定参数,我想知道应该显示哪个参数

I want to either display a message in the console or a pop up, so in case a parameter is not specified, I want to know to which should I display

类似:

if( !file.exists() ) {
    if( fromCommandLine()){
        System.out.println("File doesn't exists");
    }else if ( fromDoubleClickOnJar() ) {
        JOptionPane.showMessage(null, "File doesn't exists");
    }
 }


推荐答案

直接的回答是你不能告诉JVM是如何启动的。

The straight forward answer is that you cannot tell how the JVM was launched.

但是对于你的问题中的例子,你不需要知道如何JVM已启动。你真正需要知道的是,用户是否会看到写入控制台的消息。而这样做的方式是这样的:

But for the example use-case in your question, you don't really need to know how the JVM was launched. What you really need to know is whether the user will see a message written to the console. And the way to do that would be something like this:

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
    }
 }

控制台,而不是水密,强烈暗示控制台对象(如果存在)写入控制台,不能重定向。

The javadoc for Console, while not water tight, strongly hints that a Console object (if it exists) writes to a console and cannot be redirected.

感谢@Stephen Denne !GraphicsEnvironment.isHeadless()提示。

Thanks @Stephen Denne for the !GraphicsEnvironment.isHeadless() tip.

这篇关于有没有办法知道一个Java程序是从命令行还是从一个jar文件启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆