我已将 matlab .m 文件部署到 Windows 控制台应用程序中。我部署的 matlab 文件实际上是一个 matlab 函数,它没有参数并返回整数列表。我正在使用 java 代码运行该 .exe 进程来运行我的可执行文件。我尝试使用以下代码读取返回值:
Process process = Runtime.getRuntime().exec("epidemic.exe");
//process.waitFor();
System.out.println("....");
InputStream in = process.getInputStream(); // To read process standard output
InputStream err = process.getErrorStream(); // To read process error output
while (process.isAlive()) {
while (in.available() > 0 || err.available() > 0) {
if (in.available() > 0) {
System.out.print((char)in.read()); // You might wanna echo it to your console to see progress
}
if (err.available() > 0) {
err.read(); // You might wanna echo it to your console to see progress
}
}
Thread.sleep(1);
}
System.out.println("....");
编辑:根据建议的更改,我重新更改了我的代码。同样,它似乎没有打印返回值。如果这段代码没问题,我如何检查可执行文件是否确实返回值?
最佳答案
您的 while
循环尝试从已启动进程的标准输出读取整行。
我强调了潜在的问题。例如,如果进程不写入整行,或者写入其标准错误,则 reader.readLine()
将永远阻塞。
另请注意,进程有 2 个输出流:标准输出和标准错误。两者都有一个缓冲区,如果其中任何一个在您未读取的情况下被填满,则在尝试写入更多输出时该进程将被阻塞。
为了确保进程不会被阻止,您必须读取其两个输出流,以下是如何执行此操作的示例:
InputStream in = process.getInputStream(); // To read process standard output
InputStream err = process.getErrorStream(); // To read process error output
while (proc.isAlive()) {
while (in.available() > 0 || err.available() > 0) {
if (in.available() > 0)
in.read(); // You might wanna echo it to your console to see progress
if (err.available() > 0)
err.read(); // You might wanna echo it to your console to see progress
}
Thread.sleep(1);
}
如果你想打印从进程的输出流中读取的数据,你可以这样做:
System.out.print((char)in.read()); // read() returns int, convert it to char
关于java - Println 可执行文件的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28196619/