繁体   English   中英

在Java中执行Linux命令

[英]Executing Linux Commands in java

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

文件格式: "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);
        }
}

星号是外壳程序解释的内容,因此您需要使用外壳程序作为主进程,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};

无法确切看到作为命令传递的内容,但是在Linux上通常需要将命令和参数拆分为字符串数组,例如:

String[] cmd = {"cp", inputPath+filesPattern, destPath};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM