Java 应用程序在使用 Runtime.getRuntime() 执行命令时未从文件读取

Java application not reading from file when executing command with Runtime.getRuntime()

我有一个 Java 应用程序,它使用 Runtime.getRuntime.exec("command"); 执行命令然后它生成一个文件,我需要读取该文件以找到一个字符串,到目前为止一切正常。

问题是程序在执行命令后找不到给定的字符串,但是如果我在第一次 运行 应用程序之后注释掉行 Runtime.getRuntime.exec("command"); 并且进一步 运行s 并创建了文件,它正确地找到了字符串。似乎 getRuntime() 出于某种原因停止了 fileReader 的工作。有人知道这个的修复方法吗?

public static void main(String[] args) throws IOException{

    String[] command = new String[3];
    command[0] = "cmd.exe";
    command[1] = "/c";
    command[2] = "C:\Users\kjdah\Desktop\handle.exe -a > C:\Users\kjdah\Desktop\handles.txt";

    Runtime.getRuntime().exec(command);

    String toFind = "##?#USB#VID_04F2&PID_B2E1&MI_00#6&9f9977c&0&0000#";
    File file = new File("C:\Users\kjdah\Desktop\handles.txt");

    boolean found = false;
    String strLinePid = null;

    try {
        FileReader fstream = new FileReader(file);
        BufferedReader buffer = new BufferedReader(fstream);
        String strLine;

        while ((strLine = buffer.readLine()) != null)   {

            if(strLine.contains("pid:")){
                strLinePid = strLine;
            }

            if(strLine.contains(toFind)){
                found = true;
                break;
            }
        }

        buffer.close();
        fstream.close();

    }
    catch (Exception e){
        System.err.println("An error happened: " + e.getMessage());
        e.printStackTrace();
    }

`

Runtime#exec 创建一个并发运行的新进程。您必须等待它完成才能处理其结果。

这可以使用方法 Process#waitFor of the Process that Runtime#exec returns. Additionally, it is a good idea to check if the process was successful. Have a look at the Javadoc of Process 来完成以获取更多信息。