viki
viki

Reputation: 125

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"

Command: "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:

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);
        }
}

Upvotes: 0

Views: 101

Answers (2)

morgano
morgano

Reputation: 17422

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'.

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. So you need to do the following:

1: change your method's signature to use a String[]:

public void runtimeExec(String[] cmd)

2: call your method with this value for cmd:

String[] cmd = new String[] {"bash", "-c",
    "cp " + imputPath + filesPattern + " " + destPath};

Upvotes: 3

michael875
michael875

Reputation: 126

Can't see what exactly is passed as a command, but on linux often is necessary to split command and parameters to string array, like:

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

Upvotes: 2

Related Questions