在java中执行Linux命令

时间:2014-08-16 10:54:19

标签: java linux

我需要将特定模式的文件从一个导演复制到另一个

文件模式: "nm.cdr.*(asterisk)-2014-08-16-14*(asterisk).gz"

命令: "cp " + inputPath + filesPattern + " " + destPath;

如果我使用特定文件而不是使用*而不是它可以正常工作(对于单个文件)但是使用*的模式它不起作用。

修改1:我尝试了以下代码:

public void runtimeExec(String cmd)
{
    StringBuffer output = new StringBuffer();

        Process p;
        try
        {
            p = Runtime.getRuntime().exec(cmd);
            p.waitFor();
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";           
            while ((line = reader.readLine())!= null) {
                    output.append(line + "\n");
            }

        } 
        catch (IOException | InterruptedException e) 
        {
            LogProperties.log.error(e);
        }
}

2 个答案:

答案 0 :(得分:3)

星号是shell解释的东西,所以你需要使用shell作为主进程,Java中进程的命令行类似于bash -c '/origin/path/nm.cdr.*-2014-08-16-14*.gz /destination/path'

现在,如果您尝试在单个字符串中使用此命令,它将无法正常工作,您需要使用String[]而不是String。所以你需要做以下事情:

1:更改方法的签名以使用String[]

public void runtimeExec(String[] cmd)

2:使用cmd

的此值调用您的方法
String[] cmd = new String[] {"bash", "-c",
    "cp " + imputPath + filesPattern + " " + destPath};

答案 1 :(得分:2)

无法查看确切传递的命令,但在Linux上经常需要将命令和参数拆分为字符串数组,如:

String[] cmd = {"cp", inputPath+filesPattern, destPath};
相关问题