【问题标题】:Java - How do i run a particular DOS command through JLabelJava - 我如何通过 JLabel 运行特定的 DOS 命令
【发布时间】:2017-10-20 22:17:42
【问题描述】:

我有一个带有一些文本的 JLabel,我想通过 JLabel 运行“echo %USERNAME%”命令,以便在 NetBeans IDE 8.2 上运行代码后,它应该在 JLabel 上打印 USERNAME以下 Windows 7 最终用户的文本

例如:我有带有文本的 JLabel:“Hello Visitor” 我想在 echo %USERNAME% 的帮助下将 Visitor 更改为 USERNAME,以便它应该在 JLabel 上打印 Windows 7 最终用户的 USERNAME

谢谢

【问题讨论】:

    标签: java swing shell batch-file jlabel


    【解决方案1】:

    很抱歉回答问题with一个问题,但是您想获取帐户的用户名并将其存储在字符串中,然后将其用作某个对象的属性?

    如果是这样,有一个方法叫System.getProperty("user.name");

    这就是我对您的问题的理解,如果不正确,请致歉。此外,对于运行 shell 命令(特定于平台),我会使用 ProcessBuilder 或 Runtime.exec("%USERNAME");,具体取决于您使用的 Java 版本。对于两者中的后者,this 也会有所帮助

    【讨论】:

    • 感谢您的回复,但是有什么方法可以运行 System.getProperty("user.name");在 NetBeans 上编译代码后的 JLabel 上
    • 编译你的代码和运行它是不一样的。如果你想运行你的代码,编译是不够的,你必须让JVM执行你的代码。
    • @Brennn Oct 感谢兄弟,我终于在 Java 中的 jLabel 的帮助下运行了它,即 jLabel.setText("Welcome " + System.getProperty("user.name"));跨度>
    • 太棒了!乐于助人
    【解决方案2】:

    如果您想要的只是计算机的用户名,那么请务必使用System.getProperty("user.name");。但是,如果您想通过 Windows 命令提示符抛出其他项目,那么您可能希望通过 runCMD() 方法使用类似的东西:

    List<String> list = runCMD("/C echo %USERNAME%");
    if (!list.isEmpty()) {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
    

    控制台将显示当前用户名。

    该方法可能如下所示:

    public List<String> runCMD(String commandString) {
        // Remove CMD from the supplied Command String
        // if it exists.
        if (commandString.toLowerCase().startsWith("cmd ")) {
            commandString = commandString.substring(4);
        }
    
        List<String> result = new ArrayList<>();
        try {
            // Fire up the Command Prompt and process the
            // supplied Command String.
            Process p = Runtime.getRuntime().exec("cmd " + commandString);
            // Read the process input stream of the command prompt.
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(p.getInputStream()))) {
                String line = null;
                // Store what is in the stream into our ArrayList.
                while ((line = in.readLine()) != null) {
                    result.add(line);
                }
            }
            p.destroy(); // Kill the process
            return result;
        } 
        catch (IOException e) {
            System.err.println("runCMD() Method Error! - IO Error during processing "
                             + "of the supplied command string!\n" + e.getMessage());
            return null;
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      相关资源
      最近更新 更多