问题
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