gpt4 book ai didi

java - 是否可以获取一个字符串并将其放入 System.in 中?

转载 作者:行者123 更新时间:2023-12-01 07:36:56 24 4
gpt4 key购买 nike

我想知道是否有办法获取String - 比方说:

String str = "blabla";

然后做:

System.in.setText(str);   

我知道这行不通 - 我想知道是否有办法做到这一点。然后发送相同的字符串。就像您在控制台中写入并按 Enter 一样。

这是一个带有服务器套接字的程序,我试图通过端口发送一个String,以便其他应用程序知道如何处理它。

编辑: 我找到了一种方法,当用户在通过 System.in 发送的文本字段中写入时,将输入流重定向到文本字段。

import java.io.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class TextfieldInputStream extends InputStream implements DocumentListener {

private JTextField tf;
private String str = null;
private int pos = 0;

public TextfieldInputStream(JTextField jtf) {
tf = jtf;
}

@Override
public int read() {
//test if the available input has reached its end
//and the EOS should be returned
if(str != null && pos == str.length()){
str = null;
//this is supposed to return -1 on "end of stream"
//but I'm having a hard time locating the constant
return java.io.StreamTokenizer.TT_EOF;
}
//no input available, block until more is available because that's
//the behavior specified in the Javadocs
while (str == null || pos >= str.length()) {
try {
//according to the docs read() should block until new input is available
synchronized (this) {
this.wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
//read an additional character, return it and increment the index
return str.charAt(pos++);
}

public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}

public void insertUpdate(DocumentEvent e){
str = tf.getText() + "\n";
pos = 0;
synchronized (this) {
//maybe this should only notify() as multiple threads may
//be waiting for input and they would now race for input
this.notifyAll();
}
}

public void removeUpdate(DocumentEvent e){
// TODO Auto-generated method stub
}
}

最佳答案

package test.t100.t007;

import java.io.ByteArrayInputStream;
import java.util.Scanner;

public class SystemIn {

public static void main(String[] args) {
String str = "blabla";
ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
System.setIn(bais);
// We might use the ByteArrayInputStream here, but going with System.in..
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
System.out.println(input);
}
}

关于java - 是否可以获取一个字符串并将其放入 System.in 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10759399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com