我想在 Java 的 2 个不同类中访问相同的输入流。因此,一个类期望来自 System.in 的输入,而另一个类则写入 System.in。这可能吗?
因此,假设我的第一个类 Test.java 需要来自 System.in 的输入:
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintStream output = new PrintStream(System.out);
output.println("Enter your username: ");
String userName;
userName = input.readLine().trim();
output.println("Welcome " + userName + "!");
}
第二个类写入相同的输入:
public class Test2 {
public static void main(String[] args) throws UnsupportedEncodingException {
String data = "John";
InputStream testInput = new ByteArrayInputStream( data.getBytes("UTF-8") );
System.setIn(testInput);
}
}
上面的代码片段目前不起作用,因为我猜每个类都有自己的输入流。我该如何处理?