Java I/O How to - Take a string and put it in the System.in








Question

We would like to know how to take a string and put it in the System.in.

Answer

import java.io.ByteArrayInputStream;
import java.util.Scanner;
//ww  w . ja va 2s.  c o  m
public class Main {

    public static void main(String[] args) {
        String str = "java2s.com";
        ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
        System.setIn(bais);

        Scanner scanner = new Scanner(System.in);
        String input = scanner.next();
        System.out.println(input);
    }
}

The code above generates the following result.