我正在为一个方法写一个 "端到端 "的测试,这个方法接收命令,运行它,然后用字符串返回stdout输出。它看起来像这样。
public static String runCommand(String ... command) { }。
我需要的是一个跨平台的命令,它可以把一些东西写入控制台,因为我们有很多windowslinux机器,我需要测试在所有地方运行。我希望不要有一个 if (os == 'windows')
类型声明。
我不想 System.out.println(command)
在这里,我想执行代码并得到输出。
例如: sleep 5
在UnixLinux和Windows上都会休眠5秒,但不会输出任何东西。echo hello
在Windows上不能工作,因为 echo
是Unix终端的一个命令。
有什么想法吗?
我并不是在寻找关于这段代码的 "可测试性 "的评论。
hostname
, ping
, route
, whoami
, help
, ... ?
你必须使用 Runtime
为此。
public static String runCommand(String command) throws IOException {
String output="";
Process p=Runtime.getRuntime().exec(command); // Execute the command
InputStream is=p.getInputStream(); // Get InputStream
byte[] buf=new byte[1024]; // Increase if you expect output above 1024 characters
is.read(buf); // Read the input and write to buf
output=new String(buf).trim(); // Remove the empty bytes at the end
return output;
}
如果你也想读取任何错误,请添加以下代码。
InputStream es=p.getErrorStream();
byte[] ebuf=new byte[1024];
es.read(buf);
if(new String(ebuf).trim().length()!=0) { // If errors occured
output+="\n Errors: "+new String(ebuf).trim();
}
让我知道它是否有效 编码愉快:) 查理----------。
...
echo
hello在Windows上是行不通的,因为echo是来自Unix终端的命令。
只是出于兴趣。这还是真的吗?
我似乎可以运行 echo test
在Windows的cmd提示符下就可以了 (Windows7x64) 和 维基百科似乎也建议 echo
可在Windows平台上使用. 还有一些 Windows服务器文档中列出了 echo
作为命令. 我使用它的目的和原作者完全一样,测试子进程的执行和stdout值。(虽然来自Python)