Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java获取进程输出不需要';不要显示所有的内容_Java_Process_Processbuilder - Fatal编程技术网

使用Java获取进程输出不需要';不要显示所有的内容

使用Java获取进程输出不需要';不要显示所有的内容,java,process,processbuilder,Java,Process,Processbuilder,我正在用Java执行进程并解析它们的结果。然而,当我阅读输出时,我并没有得到所有的内容 例如,如果我使用Windows控制台执行此操作: cmd /c tasklist | FIND "java" 它表明: javaw.exe 6192 Console 1 683.668 KB java.exe 8448 Console 1 35.712 KB java.exe 7252 Console 1 35.736 KB javaw.exe

我正在用Java执行进程并解析它们的结果。然而,当我阅读输出时,我并没有得到所有的内容

例如,如果我使用Windows控制台执行此操作:

cmd /c tasklist | FIND "java"
它表明:

javaw.exe    6192 Console     1   683.668 KB
java.exe     8448 Console     1    35.712 KB
java.exe     7252 Console     1    35.736 KB
javaw.exe    3260 Console     1    76.652 KB
java.exe     9728 Console     1    35.532 KB
但是,如果我对java进程执行相同的操作,则只会显示其中两个:

java.exe     8448 Console     1    35.712 KB
javaw.exe    3260 Console     1    76.652 KB
这是代码的简化版本:

public static void printPidsOfJavaProcesses() {
    try {
        String[] params = null;
        if (isInWindows()) {
            params = new String[6];
            params[0] = "cmd";
            params[1] = "/c";
            params[2] = "tasklist";
            params[3] = "|";
            params[4] = "FIND";
            params[5] = "\"java\"";
        } else {
            ...
        }

        Process process = ProcessUtil.executeConsoleCommand(params);
        printConsoleOutput(process) 
    } catch (IOException e) {
        log.error("It was not possible to obtain the pids of the active processes");
    }
}

public static void printConsoleOutput(Process process) {
    InputStream input = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    try {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        log.error("It was not possible to obtain the process output", e);
    }
}

public static Process executeConsoleCommand(String[] params) throws IOException {

    // Create the process
    final ProcessBuilder processBuilder = new ProcessBuilder(params);

    // Redirect errors to avoid deadlocks when the buffer get full
    processBuilder.redirectErrorStream(true);

    // Launch the process
    Process process = processBuilder.start();

    return process;
}
public static List<String> getPidsOfJavaProcesses() throws ProcessException {

    List<String> pids = null;
    boolean isOnWindows = isOnWindows();

    if (isOnWindows) {
        String[] commandParams = getCommandParamsForGettingProcessesOnWindows();
        Process pr = executeConsoleCommand(commandParams);
        pids = getConsoleOutput(pr);
    } else {
        String[] commandParams = getCommandParamsForGettingProcessesOnLinux();
        Process pr = executeConsoleCommand(commandParams);
        List<String> outputLines = getConsoleOutput(pr);
        pids = getJavaPidsFromConsoleOutputOnLinux(outputLines);
    }

    return pids;
}

public static boolean isOnWindows() {
    boolean isOnWindows = false;
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().contains("windows")) {
        isOnWindows = true;
    }

    return isOnWindows;
}

private static String[] getCommandParamsForGettingProcessesOnLinux() {

    String[] params = new String[3];
    params[0] = "bash";
    params[1] = "-c";
    params[2] = "ps -fe | grep \"java\"";

    return params;
}

private static String[] getCommandParamsForGettingProcessesOnWindows() {

    String[] params = new String[11];
    params[0] = "cmd";
    params[1] = "/c";
    params[2] = "wmic";
    params[3] = "process";
    params[4] = "where";
    params[5] = "name=\"javaw.exe\"";
    params[6] = "get";
    params[7] = "processid";
    params[8] = "|";
    params[9] = "MORE";
    params[10] = "+1";

    return params;
}

public static Process executeConsoleCommand(String[] params) throws ProcessException {

    // Create the process
    final ProcessBuilder processBuilder = new ProcessBuilder(params);

    // Redirect errors to avoid deadlocks when the buffers get full.
    processBuilder.redirectErrorStream(true);

    // Launch the process
    Process process = null;
    try {
        process = processBuilder.start();
    } catch (IOException e) {
        log.error("Exception launching a process", e);
        throw new ProcessException("Exception launching a process", e);
    }

    return process;
}

public static List<String> getConsoleOutput(Process process) throws ProcessException {
    List<String> lines = new ArrayList<String>();
    InputStream input = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    try {
        String line = reader.readLine();
        while (line != null) {
            line = line.trim();
            if (!line.isEmpty()) {
                lines.add(line);
            }
            line = reader.readLine();
        }
    } catch (IOException e) {
        log.error("It was not possible to obtain the process output", e);
        throw new ProcessException("It was not possible to obtain the process output", e);
    } finally {
        try {
            if (input != null) {
                input.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            log.error("It was not possible to close the console stream", e);
            throw new ProcessException("It was not possible to close the console stream", e);
        }
    }

    return lines;
}
我在这里和Google上搜索过,大多数人都以类似的方式启动和读取进程,因此问题的原因可能与console命令有关。你知道吗?
提前感谢

我刚刚用而不是任务列表解决了它。代码如下:

public static void printPidsOfJavaProcesses() {
    try {
        String[] params = null;
        if (isInWindows()) {
            params = new String[6];
            params[0] = "cmd";
            params[1] = "/c";
            params[2] = "tasklist";
            params[3] = "|";
            params[4] = "FIND";
            params[5] = "\"java\"";
        } else {
            ...
        }

        Process process = ProcessUtil.executeConsoleCommand(params);
        printConsoleOutput(process) 
    } catch (IOException e) {
        log.error("It was not possible to obtain the pids of the active processes");
    }
}

public static void printConsoleOutput(Process process) {
    InputStream input = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    try {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        log.error("It was not possible to obtain the process output", e);
    }
}

public static Process executeConsoleCommand(String[] params) throws IOException {

    // Create the process
    final ProcessBuilder processBuilder = new ProcessBuilder(params);

    // Redirect errors to avoid deadlocks when the buffer get full
    processBuilder.redirectErrorStream(true);

    // Launch the process
    Process process = processBuilder.start();

    return process;
}
public static List<String> getPidsOfJavaProcesses() throws ProcessException {

    List<String> pids = null;
    boolean isOnWindows = isOnWindows();

    if (isOnWindows) {
        String[] commandParams = getCommandParamsForGettingProcessesOnWindows();
        Process pr = executeConsoleCommand(commandParams);
        pids = getConsoleOutput(pr);
    } else {
        String[] commandParams = getCommandParamsForGettingProcessesOnLinux();
        Process pr = executeConsoleCommand(commandParams);
        List<String> outputLines = getConsoleOutput(pr);
        pids = getJavaPidsFromConsoleOutputOnLinux(outputLines);
    }

    return pids;
}

public static boolean isOnWindows() {
    boolean isOnWindows = false;
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().contains("windows")) {
        isOnWindows = true;
    }

    return isOnWindows;
}

private static String[] getCommandParamsForGettingProcessesOnLinux() {

    String[] params = new String[3];
    params[0] = "bash";
    params[1] = "-c";
    params[2] = "ps -fe | grep \"java\"";

    return params;
}

private static String[] getCommandParamsForGettingProcessesOnWindows() {

    String[] params = new String[11];
    params[0] = "cmd";
    params[1] = "/c";
    params[2] = "wmic";
    params[3] = "process";
    params[4] = "where";
    params[5] = "name=\"javaw.exe\"";
    params[6] = "get";
    params[7] = "processid";
    params[8] = "|";
    params[9] = "MORE";
    params[10] = "+1";

    return params;
}

public static Process executeConsoleCommand(String[] params) throws ProcessException {

    // Create the process
    final ProcessBuilder processBuilder = new ProcessBuilder(params);

    // Redirect errors to avoid deadlocks when the buffers get full.
    processBuilder.redirectErrorStream(true);

    // Launch the process
    Process process = null;
    try {
        process = processBuilder.start();
    } catch (IOException e) {
        log.error("Exception launching a process", e);
        throw new ProcessException("Exception launching a process", e);
    }

    return process;
}

public static List<String> getConsoleOutput(Process process) throws ProcessException {
    List<String> lines = new ArrayList<String>();
    InputStream input = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    try {
        String line = reader.readLine();
        while (line != null) {
            line = line.trim();
            if (!line.isEmpty()) {
                lines.add(line);
            }
            line = reader.readLine();
        }
    } catch (IOException e) {
        log.error("It was not possible to obtain the process output", e);
        throw new ProcessException("It was not possible to obtain the process output", e);
    } finally {
        try {
            if (input != null) {
                input.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            log.error("It was not possible to close the console stream", e);
            throw new ProcessException("It was not possible to close the console stream", e);
        }
    }

    return lines;
}
public static List getpidsofjavaprocesss()抛出ProcessException{
列表PID=null;
布尔值isOnWindows=isOnWindows();
if(isOnWindows){
字符串[]commandParams=GetCommandParamsTargetingProcesssOnWindows();
进程pr=executeConsoleCommand(commandParams);
pids=获取控制台输出(pr);
}否则{
字符串[]commandParams=GetCommandParamsTargetingProcessOnLinux();
进程pr=executeConsoleCommand(commandParams);
列表输出行=getConsoleOutput(pr);
pids=getJavaPidsFromConsoleOutputOnLinux(输出线);
}
返回PID;
}
公共静态布尔值isOnWindows(){
布尔值isOnWindows=false;
字符串osName=System.getProperty(“os.name”);
if(osName.toLowerCase().contains(“windows”)){
isOnWindows=true;
}
返回isOnWindows;
}
私有静态字符串[]GetCommandParamsTargetingProcesssOnlinux(){
字符串[]参数=新字符串[3];
参数[0]=“bash”;
参数[1]=“-c”;
参数[2]=“ps-fe | grep\”java\”;
返回参数;
}
私有静态字符串[]GetCommandParamsTargetingProcesseSonWindows(){
字符串[]参数=新字符串[11];
参数[0]=“cmd”;
参数[1]=“/c”;
参数[2]=“wmic”;
参数[3]=“进程”;
参数[4]=“其中”;
参数[5]=“name=”javaw.exe\”;
参数[6]=“获取”;
params[7]=“processid”;
参数[8]=“|”;
参数[9]=“更多”;
参数[10]=“+1”;
返回参数;
}
公共静态进程executeConsoleCommand(字符串[]参数)引发ProcessException{
//创建流程
最终ProcessBuilder ProcessBuilder=新的ProcessBuilder(参数);
//重定向错误以避免缓冲区满时出现死锁。
processBuilder.redirectErrorStream(true);
//启动流程
Process=null;
试一试{
process=processBuilder.start();
}捕获(IOE异常){
log.error(“启动进程异常”,e);
抛出新的ProcessException(“启动进程的异常”,e);
}
返回过程;
}
公共静态列表getConsoleOutput(进程进程)引发ProcessException{
列表行=新的ArrayList();
InputStream输入=process.getInputStream();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(输入));
试一试{
字符串行=reader.readLine();
while(行!=null){
line=line.trim();
如果(!line.isEmpty()){
行。添加(行);
}
line=reader.readLine();
}
}捕获(IOE异常){
日志错误(“无法获得过程输出”,e);
抛出新的ProcessException(“无法获得进程输出”,e);
}最后{
试一试{
如果(输入!=null){
input.close();
}
if(读卡器!=null){
reader.close();
}
}捕获(IOE异常){
log.error(“无法关闭控制台流”,e);
抛出新的ProcessException(“无法关闭控制台流”,e);
}
}
回流线;
}

我对Windows命令解释器不太了解,但
|
是否是一个将左命令的输出发送到右命令的输入的管道?是的@fge,关键是获取活动进程的筛选列表,以便仅获取java进程。这类似于在linux中执行此操作:
ps-fe | grep“java”
,而
cmd/c
是为了避免在ProcessOK中使用管道时出现问题,所以有两个问题:首先,为什么要使用
cmd
tasklit
是cmd内置的吗?第二,为什么要使用
FIND
而不是Java的方法来进行过滤呢?
cmd
是我发现的一个技巧,用于使用Java执行包含管道的命令。我尝试不使用它,但出现了一个错误,因为它无法将
解析为参数。对于过滤,我可以使用
contains
方法,但我认为这样更有效。不管怎样,当我执行它时,没有
FIND
我也有同样的问题,只是出现了一些结果。如果我可以这么说的话,你引用的答案中的技巧是“不好的”;您应该使用Java本身将一个命令的输出通过管道传输到另一个命令。诚然,这并没有回答你最初的问题。