这是我的代码:
Process p=Runtime.getRuntime().exec("something command");
String s;
JFrame frame = new JFrame();
frame.setSize(600, 400);
JTextField A = new JTextField();
A.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String s = A.getText();
System.out.println("I send a text: " + s);
try{
p.getOutputStream().write(s.getBytes());
p.getOutputStream().close();
}catch(Exception ex){
ex.printStackTrace();
}
A.setText("");
}
});
frame.add(A);
frame.setVisible(true);
// Read command standard input
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
我想使用 p.getOutputStream() 发送消息两次,但问题是我需要关闭 OutputStream 才能发送。我无法再次发送,因为它已关闭。我可以重新连接OutputStream还是不需要关闭OutputStream?
谢谢:)
最佳答案
您可以调用flush()
,而不是调用close()
它刷新此输出流并强制写出所有缓冲的输出字节。然后,在将消息写入所需次数后,您可以close()
。
关于java - 流程,如何使用Outputstream发送两次消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35526956/