我如何写入标准输入(JAVA) [英] How can I write to stdIn (JAVA)
问题描述
我想使用诸如join 8"之类的输入对我的 P2P 系统进行一些测试.8 是节点号.对于我的系统,命令join 8"是从stdin读取的,但我不想在百次测试中输入一百次,所以我写了一个测试函数来随机生成节点号,然后通过调用join"命令本身.所以我希望 JAVA 编写命令而不是我自己对 stdin 的输入.我怎样才能做到这一点?目标是:当我输入test join 3"时,代码应该在1-255之间随机生成3个节点号并为它们调用join命令.我的代码现在不能正常工作:
if (command[0].equals("test")) {//测试加入if (command[1].equals("join")) {int nodenum = Integer.parseInt(command[2]);随机 rand = new Random();设置<整数>生成 = 新 LinkedHashSet();while (generated.size()
Java System
类为您提供了一种设置System.in
输入流的方法.>
该方法名为setIn
并允许您重新分配标准输入.
编辑
这是一个如何做到的例子:
InputStream fakeIn = new ByteArrayInputStream(dataYourWantToPassAsBytesArray);System.setIn(fakeIn);
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();
}
}
}
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);
这篇关于我如何写入标准输入(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!