Java - 无法从 InputStream 读取,直到 OutputStream 关闭
Java - Can't read from InputStream, until OutputStream is closed
我正在尝试读取和写入 bash/cmd。我正在使用流程构建器启动流程。
第一次读取和写入命令行就完美无缺。但是当我向命令行写入内容时,在关闭缓冲编写器之前我无法从 InputStream 中读取。当我关闭缓冲写入器时,我可以再次从命令行读取。
当我这样做时,outputStream 和 inputStream 之间是否存在冲突:
Thread thread = new Thread() {
public void run()
{
try
{
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "jdb" + path);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader bufferedReaderInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader bufferedReaderError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
String currentLine = "";
while ((currentLine = bufferedReaderInput.readLine()) != null)
{
bufferedWriter.write("hello");
bufferedWriter.flush();
//If I close the bufferedWriter here, I can read again from the bufferedReader.
}
while ((currentLine = bufferedReaderError.readLine()) != null)
{
consoleWindow.appendText(currentLine);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
thread.start();
尝试更改:
bufferedWriter.write("hello");
至:
bufferedWriter.write("hello\n");
没有 '\n' 就像在 jdb 中输入 "hello" 但不按回车键。
我正在尝试读取和写入 bash/cmd。我正在使用流程构建器启动流程。 第一次读取和写入命令行就完美无缺。但是当我向命令行写入内容时,在关闭缓冲编写器之前我无法从 InputStream 中读取。当我关闭缓冲写入器时,我可以再次从命令行读取。 当我这样做时,outputStream 和 inputStream 之间是否存在冲突:
Thread thread = new Thread() {
public void run()
{
try
{
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "jdb" + path);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader bufferedReaderInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader bufferedReaderError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
String currentLine = "";
while ((currentLine = bufferedReaderInput.readLine()) != null)
{
bufferedWriter.write("hello");
bufferedWriter.flush();
//If I close the bufferedWriter here, I can read again from the bufferedReader.
}
while ((currentLine = bufferedReaderError.readLine()) != null)
{
consoleWindow.appendText(currentLine);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
thread.start();
尝试更改:
bufferedWriter.write("hello");
至:
bufferedWriter.write("hello\n");
没有 '\n' 就像在 jdb 中输入 "hello" 但不按回车键。