How can I write to stdIn (JAVA) [duplicate]

北城以北 提交于 2019-12-11 03:02:17

问题


I want to do some tests on my P2P system by using some input like: "join 8". 8 is the Node number. For my system, the command "join 8" is read from stdin, but I don't want to type it hundred times for hundred tests, so I write a test function to randomly generate node numbers and then call the "join" command by itself. So I want JAVA to write commands instead of my own input to stdin. How can I do that? The goal is: When I input "test join 3", the code should randomly generate 3 node numbers between 1-255 and call join commands for them. My code doesn't really work now:

if (command[0].equals("test")) {
            //test join
            if (command[1].equals("join")) {
                int nodenum = Integer.parseInt(command[2]);
                Random rand = new Random();
                Set<Integer> generated = new LinkedHashSet<Integer>();
                while (generated.size() < nodenum) {
                    Integer next = rand.nextInt(255) + 1;
                    generated.add(next);
                    ProcessBuilder builder = new ProcessBuilder("java", "Test");
                    Process process = builder.start();
                    //stdIn=new BufferedReader(new InputStreamReader("join"));
                    OutputStream stdin = process.getOutputStream();
                    InputStream stdout = process.getInputStream();


                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
                    writer.write("join "+next);
                    writer.flush();
                    writer.close();

                }


            }

        }

回答1:


Java System class offer you a method to set the input stream of System.in.

The method is called setIn and allow you to re-assign the standard input.


Edit

Here an example of how you can do it :

InputStream fakeIn = new ByteArrayInputStream(dataYourWantToPassAsBytesArray);
System.setIn(fakeIn);



回答2:


It looks like you want to look at https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html.

It lets you create the data the inputStream will produce.

e.g.

public void doTestStreamStuff(){
    byte[] testData = ....
    InputStream is = new ByteArrayInputStream(testData);
    while(doStuff){
        int i = is.read();
        ...
    }
}


来源:https://stackoverflow.com/questions/29615358/how-can-i-write-to-stdin-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!