简体   繁体   English

在Java中执行Linux命令

[英]Executing Linux Commands in java

I need to copy files of specific pattern from one director to another 我需要将特定模式的文件从一位导演复制到另一位导演

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

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

If i use specific file instead of using * than it works fine(for single file) but with pattern using * it doesn't work. 如果我使用特定文件而不是使用*,那么它可以正常工作(对于单个文件),但是使用*模式则无法正常工作。

Edit 1: I tried following code: 编辑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);
        }
}

The asterisk is something interpreted by the shell, so you need to use the shell as the main process, the command line for the process in Java would be something like bash -c '/origin/path/nm.cdr.*-2014-08-16-14*.gz /destination/path' . 星号是外壳程序解释的内容,因此您需要使用外壳程序作为主进程,Java中该进程的命令行类似于bash -c '/origin/path/nm.cdr.*-2014-08-16-14*.gz /destination/path'

Now, if you try to use this command in a single string it won't work, you need to use a String[] instead of a String . 现在,如果您尝试在单个字符串中使用此命令将不起作用,则需要使用String[]而不是String So you need to do the following: 因此,您需要执行以下操作:

1: change your method's signature to use a String[] : 1:将方法的签名更改为使用String[]

public void runtimeExec(String[] cmd)

2: call your method with this value for 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