java.io.IOException:管道被关闭在Windows上是抛出的,但在Linux上运行良好



我正在尝试使用Java中的Runtime.getRuntime.exec()运行命令。

Runtime r = Runtime.getRuntime(); 
Process process = r.exec("telnet 172.16.221.87 "); 
InputStream is = process.getInputStream(); 
OutputStream os = process.getOutputStream(); 
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os));
br.write("ditechrn");
br.flush(); // The exception is coming on last line that is br.flush();

当我在Linux中运行代码时,它可以正常工作。但当相同的代码在Windows上运行时,它会抛出以下错误:

java.io.IOException: The pipe is being closed
        at java.io.FileOutputStream.writeBytes(Native Method)
        at java.io.FileOutputStream.write(Unknown Source)
        at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
        at java.io.BufferedOutputStream.flush(Unknown Source)
        at sun.nio.cs.StreamEncoder.implFlush(Unknown Source)
        at sun.nio.cs.StreamEncoder.flush(Unknown Source)
        at java.io.OutputStreamWriter.flush(Unknown Source)
        at java.io.BufferedWriter.flush(Unknown Source)
        at com.telnet.ConnectToTelnet.doTelnet(ConnectToTelnet.java:132)
        at com.telnet.ConnectToTelnet.main(ConnectToTelnet.java:16)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)

您需要读取进程的输出。它几乎可以肯定地告诉了你一些你在登录阶段忽略了的东西。您需要启动两个单独的线程来读取stdoutstderr,,或者使用ProcessProcessBuilder类,合并stderrstdout,然后使用一个线程。

让线程暂时打印输出。这将确切地告诉你当前的问题是什么。更常见的情况是,你应该在写用户名之前等待login:提示,在写密码之前等待password:提示,依此类推,以完成在Telnet会话中要做的所有其他事情:如果你遇到任何意外,你需要做出相应的反应。

一味地在进程中推波助澜只会导致更多像这样的谜题。

相关内容