java - 流程,如何使用Outputstream发送两次消息

标签 java

这是我的代码:

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/

相关文章:

java - 使用 asyncTask 为 ListView 加载位图时出现 RejectedExecutionException

java - 将网格集成到页面对象模型中

java - 使用共享资源拆分文件并处理每个部分

java - 如何移动JPanel中图形的位置

java - "Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set WindowActionBar to false in your theme to use a toolbar instead"

java - 结束 BroadcastReceiver 中的 Android Activity ?

java - 如何为实例变量设置默认值?

java - WebView 不会在 Android 2.x 中滚动

java空值检查语法差异

Java:为什么 NumberFormatException 不扩展 ParseException?