문제

Right now I have this

ByteArrayInputStream in = new ByteArrayInputStream("2".getBytes());
System.setIn(in);

//code that does something with user inputs

But the issue is that in //code that does something I have multiple user input prompts, is it possible to form a list of the user input and have it pick up the corresponding input when the time comes? I tried doing silly things like "2\n2\n10\nHello\n".getBytes() but that didn't work.

EDIT:

I am getting my user input with a Scanner object:

Scanner inputScanner = new Scanner(System.in);
inputScanner.nextLine();
도움이 되었습니까?

해결책

Just using a "new line" should be enough.

String simulatedUserInput = "input1" + System.getProperty("line.separator")
    + "input2" + System.getProperty("line.separator");

InputStream savedStandardInputStream = System.in;
System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes()));

// code that needs multiple user inputs

System.setIn(savedStandardInputStream);

다른 팁

You can do like this:

  1. Construct a DelayQueue with your simulated input plus the delay time.

  2. Extend the BytArrayInputStream and override the read() method to read a DelayQueue when read() is called.

EDIT: sample code (not fully implemented - am on a tel meeting)

public class DelayedString implements Delayed {

    private final long delayInMillis;

    private final String content;

    public DelayedString(long delay, String content) {
        this.delayInMillis = delay;
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public long getDelay(TimeUnit timeUnit) {
        return TimeUnit.MILLISECONDS.convert(delayInMillis, timeUnit);
    }
}

public class MyInputStream implements InputStream {

    private ByteBuffer buffer = ByteBuffer.allocate(8192);

    private final DelayQueue<DelayString> queue;

    public MyInputStream(DelayQueue<DelayString> queue) {
        this.queue = queue;
    }

     public int read() {
         updateBuffer();
         if (!buffer.isEmpty()) {
            // deliver content inside buffer
         }
     }

     public int read(char[] buffer, int count) {
         updateBuffer();
         // deliver content in byte buffer into buffer
     }

     protected void updateBuffer() {
         for (DelayedString s = queue.peek(); s != null; ) {
             if (buffer.capacity() > buffer.limit() + s.getContent().length()) {
                 s = queue.poll();
                 buffer.append(s.getContent());
             } else {
                 break;
             }
         }
     }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top