[英]Unable to execute Unix command through Java code
case "BVT Tool":
System.out.println("Inside BVT Tool");
try {
String[] command1 = new String[] {"mv $FileName /bgw/feeds/ibs/incoming/"};
Runtime.getRuntime().exec(command1);
} catch(IOException e) {
System.out.println("execption is :"+ e);
e.printStackTrace();
}
break;
我无法执行Unix命令。 它显示以下异常:
java.io.IOException: Cannot run program mv $FileName /bgw/feeds/ibs/incoming/":
CreateProcess error=2, The system cannot find the file specified.
我在大多数情况下都同意@Reimeus,但我想指出的是,您收到此特定错误消息的原因是exec的两个重载版本之间存在交叉污染:
String command1 = "mv $FileName /bgw/feeds/ibs/incoming/";
Runtime.getRuntime().exec(command1);
可行- 如果您使用需要一个字符串的重载版本,则可以在一个字符串中指定命令及其参数
String[] command1 = new String[] {"mv", "$FileName", "/bgw/feeds/ibs/incoming/"};
Runtime.getRuntime().exec(command1);
也可以使用,因为它使用的是exec版本,期望使用String数组 。 该版本要求命令及其参数位于单独的字符串中
请注意,我在这里假设$Filename
实际上是文件的名称,因此不会进行基于shell的替换。
编辑:如果FileName
是变量名,如您似乎在注释中的其他地方建议,请尝试
String[] command1 = new String[] {"mv", FileName, "/bgw/feeds/ibs/incoming/"};
但是:使用Commons IO,您可以做
FileUtils.moveFileToDirectory(new File(FileName), new File("/bgw/feeds/ibs/incoming/") , true);
这是
除了Runtime.exec
是一种过时的运行命令方法之外,
完整的String
被解释为可执行命令。 您需要在String
数组中使用单个标记。 另外,您需要使用外壳程序来解释$FileName
变量
String[] command1 = {"bash", "-c", "mv", "$FileName", "/bgw/feeds/ibs/incoming/"};
首先,您可能应该使用ProcessBuilder 。 您拥有的命令是“ mv”,其余应为参数,
// I'm not sure about $FileName, that's probably meant to be a shell replace
// and here there is no shell.
ProcessBuilder pb = new ProcessBuilder("mv",
System.getenv("FileName"), "/bgw/feeds/ibs/incoming/");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.