我正在尝试运行OSX命令,该命令是将某些plist转换为json格式的plutil。我在终端中使用的命令是
plutil -convert json -o - '/Users/chris/project/temp tutoral/project.plist'
这个带有白色间距的路径名的命令在我的终端中工作正常,撇号(“)符号覆盖了路径名,但问题是在java的Runtime.getRuntime().exec(cmdStr)
下面运行这个命令是我写的代码< / p>
public static void main(String args[]){
LinkedList<String> output = new LinkedList<String>();
String cmdStr = "plutil -convert json -o - /Users/chris/project/temp tutoral/project.plist";
//String cmdStr = " plutil -convert json -o - '/Users/chris/project/temp tutoral/project.plist'";
//String [] cmdStr ={ "plutil -convert json -o - ", "\"Users/chris/project/temp tutoral/project.plist\""};
Process p;
try {
p = Runtime.getRuntime().exec(cmdStr);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.add(line);
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
如果我运行此代码,它会给我一个错误
'Users/chris/project/temp: file does not exist or is not readable or is not a regular file (Error Domain=NSCocoaErrorDomain Code=260 "The file “temp” couldn’t be opened because there is no such file." UserInfo=0x7fd6b1c01510 {NSFilePath='Users/chris/project/temp, NSUnderlyingError=0x7fd6b1c01280 "The operation couldn’t be completed. No such file or directory"})
tutoral/project.plist': file does not exist or is not readable or is not a regular file (Error Domain=NSCocoaErrorDomain Code=260 "The file “project.plist” couldn’t be opened because there is no such file." UserInfo=0x7fd6b1d6dd00 {NSFilePath=tutoral/project.plist', NSUnderlyingError=0x7fd6b1d6c6b0 "The operation couldn’t be completed. No such file or directory"})
我也试过了,
但他们没有工作。
如果我在安排命令或任何语法错误方面做错了,请提供建议。提前谢谢。
答案 0 :(得分:1)
试试这个
/Users/chris/project/temp\ tutoral/project.plist
编辑:我在第一篇文章
上错误地反对了答案 1 :(得分:1)
调用Runtime.getRuntime().exec(cmdStr)
是一种便捷方法 - 使用数组调用命令的快捷方式。它将命令字符串拆分为空格,然后使用生成的数组运行命令。
因此,如果你给它一个字符串,其中任何参数都包含空格,它不像shell那样解析引号,但只是把它分成如下部分:
// Bad array created by automatic tokenization of command string
String[] cmdArr = { "plutil",
"-convert",
"json",
"-o",
"-",
"'/Users/chris/project/temp",
"tutoral/project.plist'" };
当然,这不是你想要的。所以在这种情况下,你应该将命令分解为你自己的数组。每个参数都应该在数组中有自己的元素,并且您不需要为包含空格的参数添加额外的引用:
// Correct array
String[] cmdArr = { "plutil",
"-convert",
"json",
"-o",
"-",
"/Users/chris/project/temp tutoral/project.plist" };
请注意,启动流程的首选方法是使用ProcessBuilder
,例如:
p = new ProcessBuilder("plutil",
"-convert",
"json",
"-o",
"-",
"/Users/chris/project/temp tutoral/project.plist")
.start();
ProcessBuilder
提供了更多可能性,并且不鼓励使用Runtime.exec
。