5

Possible Duplicate:
Writing data to System.in

We know that System.in (Standard Input) is connected to console. So whenever we write in console it will flow to this stream. But is there any way to pass value to this Standard Input without entering from console, i.e. like System.in = "ABCD". I just want to imitate as the value is passing from console.

Community
  • 1
  • 1
Angom
  • 721
  • 1
  • 11
  • 27
  • what exactly you want to do with that? I sounds something ODD. Actually you read what is there in System.in and NOT assign to it. – Fahim Parkar Oct 23 '12 at 10:45

2 Answers2

13

Yes, there is. Use System.setIn(InputStream in).

You can supply any subtype of InputStream as well, so if you want to supply a specific value, you can use the StringBufferInputStream, like so:

StringBufferInputStream s = new StringBufferInputStream("ABCD");
System.setIn(s);
mthmulders
  • 9,483
  • 4
  • 37
  • 54
  • 1
    +1 though it's declared as `public final static InputStream` – Subhrajyoti Majumder Oct 23 '12 at 10:53
  • But it is not working for Multiple threads. I used System.setIn(s) in one thread and in the another thread I am using Scanner.nextLine(). When I pass the value to System.SetIn from one thread it did not make any effect to the other thread in which Scanner.nextLine() is used. Is there any way to make it work in multiple thread? – Angom Oct 23 '12 at 11:19
  • 2
    As I read it, you have already created a `Scanner` in the second thread, *before* changing `System.in` in the first thread. The scanner holds a reference to the `InputStream` supplied to it during creation. If you'd call `System.setIn(...)` from the first thread *before* creating the `Scanner` in the second thread, it should work without problems. – mthmulders Oct 23 '12 at 11:22
  • Yes It works. I put Thread.currentThread().sleep(10000) (i.e 10 sec delay) and after that I created the Scanner. Even though it works it doesn't meet my requirement as I dont like to put delay. I think it is better to create a new Question... :) – Angom Oct 25 '12 at 09:06
  • Currently (2018) this solution is deprecated. – Huluvu424242 May 12 '18 at 09:54
  • whats the correct way now? – john k Jul 11 '18 at 02:00
  • Neither Java 9 nor Java 10 mark `System.setIn` as being deprecated. – mthmulders Jul 11 '18 at 06:30
0

I think that instead of having your method directly access System.in:

public void process() {

    byte b[] = new byte[4000];
    int bytesRead = System.in.read(b);

    ...

}

You should factor that out so that an input stream is passed into the method:

public void run() {

    process(System.in);

}

public void process(InputStream is) {

    byte b[] = new byte[4000];
    int bytesRead = is.read(b);

    ...

}

This gives you the same behavior, but lets you invoke the business logic with input streams of your own devising for test purposes, too.

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59