首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在java程序中运行jps -l命令并获取输出

在java程序中运行jps -l命令并获取输出
EN

Stack Overflow用户
提问于 2021-10-26 11:05:38
回答 2查看 57关注 0票数 1

我必须在我的java程序中运行jps -l命令并获取输出。我已经尝试了下面提到的代码,但它不起作用。

代码语言:javascript
代码运行次数:0
运行
复制
Runtime rt = Runtime.getRuntime();
proc = rt.exec("jps -l");
代码语言:javascript
代码运行次数:0
运行
复制
Runtime rt = Runtime.getRuntime();
proc = rt.exec("cmd.exe /c start jps -l");
代码语言:javascript
代码运行次数:0
运行
复制
Runtime rt = Runtime.getRuntime();
proc = rt.exec("powershell.exe jps -l");

每次程序输出为:

代码语言:javascript
代码运行次数:0
运行
复制
Cannot run program "jps -l": CreateProcess error=2, The system cannot find the file specified

有没有办法运行"jps -l“并获取输出?

EN

回答 2

Stack Overflow用户

发布于 2021-10-26 12:39:52

jps很可能不在系统路径上。您仍然可以运行该可执行文件,只需提供绝对路径,例如

代码语言:javascript
代码运行次数:0
运行
复制
"c:\Program Files\Java\openjdk-17.0.2\bin\jps.exe" -l

注意,“Program Files”包含一个需要转义的空格。

票数 0
EN

Stack Overflow用户

发布于 2021-10-26 12:42:47

您需要为Java设置环境变量,有关如何设置,请参考how to set java path

证明:

代码语言:javascript
代码运行次数:0
运行
复制
package com.example.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("jps -l");
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        // Read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // Read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
        System.out.println("Done");
    }
}

输出:

代码语言:javascript
代码运行次数:0
运行
复制
Here is the standard output of the command:

17556 jdk.jcmd/sun.tools.jps.Jps
13320 com.example.demo.Test
22636 Eclipse
Here is the standard error of the command (if any):

Done

环境变量:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69721968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档