0

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?

Dave
  • 391
  • 3
  • 5
  • 13
  • `writes to System.in`? `write on System.out`. – Braj Apr 07 '14 at 20:09
  • What is `System.setIn(testInput);`? – Braj Apr 07 '14 at 20:10
  • `System.out` is global in the application. You can use it anywhere to write on console. – Braj Apr 07 '14 at 20:11
  • Two `main` methods usually mean that you have 2 separate applications. "global to the application" does not cover that. You can however use the [commandline to pipe](http://technet.microsoft.com/en-us/library/bb490982.aspx) one app's output to the input of another app – zapl Apr 07 '14 at 20:15
  • See this question: http://stackoverflow.com/questions/1680898/communication-between-two-separate-java-desktop-applications Although the question is about communicating between 2 different desktop applications the solutions apply to command-line applications as well. Check out the first 3 answers. – Mike B Apr 07 '14 at 20:20

1 Answers1

0

I would suggest redesigning. Create a main class that spawns two other threads that write to PipedInputStream http://docs.oracle.com/javase/7/docs/api/java/io/PipedInputStream.html and PipedOutputStream http://docs.oracle.com/javase/7/docs/api/java/io/PipedOutputStream.html .

Here's a tutorial on how to do it, it clearly explains how: io-pipestream-example

Remember System.in should not be written to, this is for program arguments in the main.

Robert
  • 53
  • 4