我正在开发新项目。我试图通过Java的以太网向外部计算机(Linux)发送命令。我正在使用Jsch创建shell连接。我将shell输入和输出设置为System.out和System.in。如何将System.in重定向到JavaFX TextField?
((ChannelShell)channel).setInputStream(System.in);
((ChannelShell)channel).setOutputStream(System.out);
它在控制台中工作!但我需要从javafx GUI应用程序中远程执行它。我已经解决了的System.out的重定向到文本区:
public void redirectOutputStream() {
OutputStream out = new OutputStream() {
private final StringBuilder sb = new StringBuilder();
@Override
public void write(int b) throws IOException {
if (b == '\r') {
return;
}
if (b == '\n') {
final String tmp = sb.toString() + "\n";
text.add(tmp);
updateText(text);
sb.setLength(0);
} else {
sb.append((char) b);
}
}
};
System.setOut(new PrintStream(out, true));
// System.setErr(new PrintStream(out, true));
}
但现在我也需要System.in重定向到文本字段,让我可以写的东西到文本字段,按回车键,并通过外壳将其发送至外部电脑。
任何帮助将不胜感激。谢谢!
编辑: 对不起,仍然不为我工作:(... 现在我有这样一段代码(我使用JavaFX):
/** Tmp queue for standard input redirecting */
BlockingQueue<Integer> stdInQueue = new LinkedBlockingQueue<>();
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
redirectOutputStream();
redirectInputStream();
}
/** redirects standard System.out to GUI command_window */
public void redirectOutputStream() {
OutputStream out = new OutputStream() {
private final StringBuilder sb = new StringBuilder();
@Override
public void write(int b) throws IOException {
if (b == '\r') {
return;
}
if (b == '\n') {
final String tmp = sb.toString() + "\n";
text.add(tmp);
updateText(text);
sb.setLength(0);
} else {
sb.append((char) b);
}
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
/** redirects standard System.in to GUI command_line */
public void redirectInputStream() {
InputStream in = new InputStream() {
@Override
public int read() throws IOException {
try {
int c = stdInQueue.take().intValue();
return c;
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
return -1;
}
}
};
System.setIn(in);
}
@FXML
void sendButtonPressed(ActionEvent event) {
if (!command_line.getText().isEmpty()) {
for (char c : command_line.getText().toCharArray()) {
System.out.write(new Integer(c)); //display in ListView (output)
stdInQueue.add(new Integer(c));
}
System.out.write(new Integer('\n')); //display in ListView (output)
stdInQueue.add(new Integer('\n'));
command_line.clear();
}
}
系统的重定向。这是显示在javafx列表视图
问题仍然是在ListView下我有一个“命令行”javafx TextField,我需要写入一些ssh命令到这个TextField并重定向它到System.in时按下“enter”或点击“发送“按钮。
我需要这样做的原因是我使用SSH通信,它是为System.in和System.out设置的。它完全适用于控制台(测试过),但不适用于我的GUI应用程序。
感谢您的任何进一步的建议!
如果您可以创建链接到文本字段的InputStream,请尝试使用'System.setIn(...)'。 – Thomas
对不起,我不知道如何编辑评论...我曾尝试使用System.setIn(new InputStream());但是我没有使用过滤“read()”方法。 – Zuzana