Java运行时执行与路径名称上的白色空间

我正在尝试运行OSX命令,该命令是将某些plist转换为json格式的plutil。 我在终端中使用的命令是

plutil -convert json -o - '/Users/chris/project/temp tutoral/project.plist' 

这个带有白色间距的路径名的命令在我的终端中工作正常,撇号(“)符号覆盖了路径名,但问题是在java的Runtime.getRuntime().exec(cmdStr)运行这个命令Runtime.getRuntime().exec(cmdStr)下面是我的代码写

 public static void main(String args[]){ LinkedList output = new LinkedList(); 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"}) 

我也尝试过,

  • 在命令字符串中放入撇号
  • 按照我的几个站点的建议更改数组字符串中的命令

但他们没有工作。

如果我在安排我的命令或任何语法错误时做错了,请通知我。 提前致谢。

调用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

试试这个

 /Users/chris/project/temp\ tutoral/project.plist 

编辑:我错误地在我的第一篇文章中反对