有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用shell命令的java

因此,尝试使用“cp”将文件从一个位置复制到另一个位置-该文件以包含空格的文件名命名(“test”)。在shell(bash)中调用命令时,它工作正常,但从java调用时失败。我使用转义字符。代码:

import java.io.*;

public class Test {

  private static String shellify(String path) {
    String ret = path;
    System.out.println("shellify got: " + ret);
    ret = ret.replace​(" ", "\\ ");
    System.out.println("shellify returns: " + ret);
    return ret;
  }    

  private static boolean copy(String source, String target) {
    String the_command = ""; // will be global later
    boolean ret = false;
    try {
      Runtime rt = Runtime.getRuntime();
      String source_sh = shellify(source);
      String target_sh = shellify(target);
      the_command = new String
    ("cp -vf " + source_sh + " " + target_sh);
      System.out.println("copy execing: " + the_command);
      Process p = rt.exec(the_command);
      InputStream is = p.getInputStream();
      BufferedReader br = new BufferedReader
    (new InputStreamReader(is));
      String reply = br.readLine();
      System.out.println("Outcome; " + reply);
      ret = (reply != null) && reply.contains("->");
    } catch(Exception e) {
      System.out.println(e.getMessage());
    }
    the_command = "";
    return ret;
  }

  public static void main(String[] args) {
    String source = "test1/test test";
    String target = "test2/test test";
    if(copy(source, target))
      System.out.println("Copy was successful");
    else
      System.out.println("Copy failed");
  }

}

。。。结果是这样的

shellify got: test1/test test
shellify returns: test1/test\ test
shellify got: test2/test test
shellify returns: test2/test\ test
copy execing: cp -vf test1/test\ test test2/test\ test
Outcome; null
Copy failed

然而,如果我使用bash,复制成功了(令人大吃一惊)

Sino-Logic-IV:bildbackup dr_xemacs$ cp -vf test1/test\ test test2/test\ test
test1/test test -> test2/test test

谁能告诉我这是为什么?复制没有空格的文件效果很好

/dr_xemacs


共 (1) 个答案

  1. # 1 楼答案

    您应该单独传递参数,它们不需要在shellify中转义,因为字符串[]版本的exec将每个参数单独作为一个参数提供给脚本,即使它们包含空格:

    String[]the_command = new String[] {"cp","-vf", source, target);
    

    如果cp不在某个路径目录中,或者您可以完全限定the_command [0]中可执行cp的路径,则可能需要修复Java VM可用的路径

    您的代码缺少一行来检查cp/进程退出代码,请在使用STDOUT/getInputStream()后添加waitFor

    int rc = p.waitFor();