无法通过Java代码执行Unix命令
我无法执行Unix命令。它显示以下异常:无法通过Java代码执行Unix命令,java,unix,Java,Unix,我无法执行Unix命令。它显示以下异常: 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) {
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;
除了
Runtime.exec
是一种非常过时的运行命令的方法之外
完整的字符串
被解释为可执行命令。您需要在字符串数组中使用单个令牌。此外,你需要
使用shell解释$FileName
变量
java.io.IOException: Cannot run program mv $FileName /bgw/feeds/ibs/incoming/":
CreateProcess error=2, The system cannot find the file specified.
首先,您可能应该使用。您拥有的命令是“mv”,其余的应该是参数
String[] command1 = {"bash", "-c", "mv", "$FileName", "/bgw/feeds/ibs/incoming/"};
我同意@Reimeus的大多数观点,但我想指出的是,您收到此特定错误消息的原因是两个重载版本的exec之间的交叉污染:
// 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/");
将起作用-允许在一个字符串中指定命令及其参数
也会起作用,因为它使用了。该版本要求命令及其参数在单独的字符串中
请注意,我在这里假设$Filename
实际上是文件名,因此不会发生基于shell的替换
编辑:如果FileName
是一个变量名,正如您在注释中的其他地方所建议的那样,请尝试
String[] command1 = new String[] {"mv", "$FileName", "/bgw/feeds/ibs/incoming/"};
Runtime.getRuntime().exec(command1);
但是:有了你就可以了
String[] command1 = new String[] {"mv", FileName, "/bgw/feeds/ibs/incoming/"};
那是
在Mac、Windows和Linux之间完全可移植(您的版本无法在Windows上运行)
速度更快,因为它不需要生成外部进程
在出现问题时为您提供更多信息
实际上,FileName是一个变量,它从包含文件名的文本框中获取输入。我尝试过,但它引发了以下异常:execption is:java.io.IOException:Cannot run program“mv”:CreateProcess error=2,系统找不到指定的文件what do哪个mv
返回?您使用的是什么Unix衍生工具?我对AIX了解不够,无法知道它将mv存储在何处,这就是为什么我建议使用命令which mv
,它将为您提供mv的完整路径,您可以将其作为exec的第一个参数。然而,在我看来,你真的应该看一看基于Commons IO的解决方案,原因在我的帖子中列出。
String[] command1 = new String[] {"mv", FileName, "/bgw/feeds/ibs/incoming/"};
FileUtils.moveFileToDirectory(new File(FileName), new File("/bgw/feeds/ibs/incoming/") , true);