如何复制文件名中带空格的文件

How to copy files with spaces in filename

我将 java 代码写入 linux 系统上的 cp 文件。它适用于文件名中没有空格的文件。但是,无论我用 " 引用整个路径还是对字符串进行转义,它都不适用于文件名中的空格。根据我捕获的标准错误,该命令似乎是有效格式。但是,如果我手动执行命令终端(带引号的路径),确实有效。

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

如何让它工作?

不要使用 exec(String command), use 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));