[英]Get all output to console from a Process in java
I'm working on an application to act as a 'wrapper' around another another application, in this case I'm working on a wrapper in java to go around a TF2 server. 我正在一个应用程序上充当另一个应用程序的“包装器”,在这种情况下,我正在Java中的包装器上运行以围绕TF2服务器。 However, I'm running into a rather odd issue with getting the output from the console to appear. 但是,在从控制台显示输出时遇到了一个很奇怪的问题。 Even if I redirect the error stream so that it will go with the input stream, the output to console will cut off after a certain point. 即使我重定向错误流以便与输入流一起使用,控制台的输出也会在特定时间点后切断。 I can connect to the server in TF2, so I know for a fact that it's launched. 我可以在TF2中连接到服务器,因此我知道它已经启动。
The code for the wrapper: 包装程序的代码:
public class TF2Wrapper {
public static void main(String[] args) throws IOException {
ProcessBuilder process = new ProcessBuilder("./srcds_run","+map pl_badwater","+port 27015","2>&1");
process.redirectErrorStream(true);
Process server = process.start();
BufferedReader inputStream = new BufferedReader(new InputStreamReader(server.getInputStream()));
String s;
while((s = inputStream.readLine()) != null)
{
System.out.println(s);
}
}
It will read the output up until the second time this line appears: 'Calling BreakpadMiniDumpSystemInit',then no further console output appears, or atleast is picked up by the application. 它将一直读取输出,直到第二次出现此行:'Calling BreakpadMiniDumpSystemInit',然后不再显示任何控制台输出,或由应用程序至少拾取。
Is there anything I can do to fix this or is that not possible? 我能做些什么来解决这个问题还是不可能?
Edit: My guess is it has something to do with the buffering, as trying to do this with python works fine. 编辑:我的猜测是它与缓冲有关,因为尝试使用python可以正常工作。
Instead of using BufferedReader use ByteArrayOutputStream 而不是使用BufferedReader,请使用ByteArrayOutputStream
public class Example {
public static void main(String[] args) throws IOException,
InterruptedException {
InputStream inputStream = null;
ByteArrayOutputStream arrayOutputStream = null;
//in case of window
ProcessBuilder builder = new ProcessBuilder("ipconfig");
try {
Process process = builder.start();
inputStream = process.getInputStream();
byte[] b = new byte[1024];
int size = 0;
arrayOutputStream = new ByteArrayOutputStream();
while ((size = inputStream.read(b)) != -1) {
arrayOutputStream.write(b, 0, size);
}
System.out.println(new String(arrayOutputStream.toByteArray()));
} catch (Exception e) {
e.getStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (arrayOutputStream != null)
arrayOutputStream.close();
} catch (Exception exception) {
exception.getStackTrace();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.