似乎有语法问题:
thufir@dur:~/NetBeansProjects/mud$
thufir@dur:~/NetBeansProjects/mud$ telnet localhost
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
thufir@dur:~/NetBeansProjects/mud$
thufir@dur:~/NetBeansProjects/mud$ gradle clean run
> Task :run FAILED
Exception in thread "main" java.io.IOException: Cannot run program "telnet localhost": error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at mud.App.telnet(App.java:29)
at mud.App.main(App.java:33)
Caused by: java.io.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:340)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:271)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 3 more
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':run'.
> Process 'command '/home/thufir/.sdkman/candidates/java/11.0.7.hs-adpt/bin/java'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 916ms
3 actionable tasks: 3 executed
thufir@dur:~/NetBeansProjects/mud$
代码:
/*
* This Java source file was generated by the Gradle 'init' task.
sh -c telnet rainmaker.wunderground.com 3000 | tee weather.txt
telnet rainmaker.wunderground.com | tee -a -i telnet.log
*/
package mud;
import java.io.IOException;
import java.util.logging.Logger;
public class App {
private final static Logger log = Logger.getLogger(App.class.getName());
private void telnet() throws IOException {
String s = "telnet rainmaker.wunderground.com | tee -a -i telnet.log";
String t = "cmd /c telnet localhost 4445";
String u = "telnet localhost 4445 | tee -a -i /home/thufir/telnet.log";
String v = "telnet localhost";
log.fine(s);
ProcessBuilder processBuilder = new ProcessBuilder(v);
Process process = processBuilder.start();
}
public static void main(String[] args) throws IOException {
new App().telnet();
}
}
如何使用exec
从Java调用telnet并将日志传送到文件?
另请参见:
How to send a String via Telnet?
阅读the ProcessBuilder
documentation,您需要提供字符串的[[list,第一个是要执行的命令,其余的是命令的参数。
ProcessBuilder
作为一个命令调用。您需要做例如
telnet localhost
ProcessBuilder processBuilder = new ProcessBuilder("telnet", "localhost");