0

Am running .exe file from java code using ProcessBulider, the code I have written is given below. The .exe file takes Input.txt(placed in same directory) as input and provide 3 output file in same directory.

public void ExeternalFileProcessing() throws IOException, InterruptedException {

    String executableFileName = "I:/Rod/test.exe;

    ProcessBuilder processBuilderObject=new ProcessBuilder(executableFileName,"Input.txt");

    File absoluteDirectory = new File("I:/Rod");

    processBuilderObject.directory(absoluteDirectory);

    Process process = processBuilderObject.start();

    process.waitFor();
}

this process is working fine by call ExeternalFileProcessing(). Now am doing validation process, If there is any crash/.exe file doesn't run, I should get the error message how can I get error message?

Note: It would be better that error message be simple like run successful/doesn't run successful or simply true/false, so that I can put this in If condition to continue the remaining process.

4

2 回答 2

1

您可以添加异常处理程序以获取错误消息。

public void externalFileProcessing() {

    String executableFileName = "I:/Rod/test.exe";

    ProcessBuilder processBuilderObject = new ProcessBuilder(
            executableFileName, "Input.txt");

    File absoluteDirectory = new File("I:/Rod");

    processBuilderObject.directory(absoluteDirectory);


    try {
        Process process = processBuilderObject.start();
        process.waitFor();
        // this code will be executed if the process works
                    System.out.println("works");
    } catch (IOException e) {
        // this code will be executed if a IOException happens "e.getMessage()" will have an error
        e.printStackTrace();
    } catch (InterruptedException e) {
        // this code will be executed if the thread is interrupted
        e.printStackTrace();
    }
}

但是最好在调用函数中处理它,方法是在调用函数中放置一个 try catch 处理程序并在那里处理它。

于 2013-09-10T08:07:46.290 回答
0

它是第三方 .exe 还是您可以访问其来源?如果是这样,您可以使用基本的系统输出(例如控制台的 couts)。可以使用以下方式将这些输出重定向到您的 java 应用程序:

InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

String line = "";
while ((line = br.readLine()) != null) {        
    if(line.equals("something")) {
        // do something
    }
}
br.close();

这就是我做这样的事情的方式,而且总的来说效果很好。但我必须承认,我不能说/保证,这是做到这一点的方法。更高级的方法可能是使用StreamGobbler(参见清单 4.5)来处理 .exe 的输出。让我知道它是否对您有帮助。

于 2013-09-10T08:06:08.387 回答