I'd like to access the same input stream in 2 different classes in Java. So one class expects an input from System.in while another class writes to System.in. Is this possible?
So let's say my first class Test.java expects an input from 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 + "!");
}
And a second class writes to the same input:
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);
}
}
The above code snippets don't work currently, because I'm guessing each class has its own input stream. How can I approach this?