我在linux系统上为cp文件编写了java代码。它适用于文件名中没有空格的文件。但是它不能用于文件名中的空格,无论我是用“或者转义字符串引用整个路径。根据我捕获的标准错误,似乎命令是有效格式。但是如果我在一个手动执行命令终端(带引号的路径),确实有效。
String file1 = "/Users/djiao/Work/moonshot/immunopath/2009-0135, 2009-0322, 2005-0027, 2006-0080 Summary.xlsx";
String file2 = "/Users/djiao/Work/moonshot/data/dev/immunopath/2009-0135, 2009-0322, 2005-0027, 2006-0080 Summary_01062016105940.xlsx";
String cmd = "cp " + file1 + " " + file2;
String cmdWithQuotes = "cp \"" + file1 + "\" \"" + file2 + "\"";
String cmdEscape = StringEscapeUtils.escapeJava(cmd);
System.out.println(cmd);
List<String> files = new ArrayList<String>();
try {
Process p = Runtime.getRuntime().exec(cmdWithQuotes);
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
// print out output and error running the commmand
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String outStr = null;
while ((outStr = stdInput.readLine()) != null) {
System.out.println(outStr);
}
String errStr = null;
while ((errStr = stdError.readLine()) != null) {
System.out.println(errStr);
}
} catch (IOException e) {
e.printStackTrace();
}
Stderr如果在代码中执行cmdWithQuotes或cmdEscape是:
usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file
cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory
如何让它发挥作用?
答案 0 :(得分:1)
请勿使用exec(String command)
,而是使用exec(String[] cmdarray)
:
Runtime.getRuntime().exec(new String[] { "cp", file1, file2 });
这将根据需要引用参数。
更好的是,在Java 7+中使用Files.copy(Path source, Path target, CopyOption... options)
:
Files.copy(Paths.get(file1), Paths.get(file2));