简体   繁体   中英

unable to execute terminal command from java code

I want to execute terminal commands,for example cp , from within the java program. The code that I am trying is:

    public String executeCommand(){
Process p;
    String[] str = {"/bin/bash", "-c", "cp", "/Users/Desktop/abc.csv",  "/Users/Desktop/folder1/"};
            try {

                p = Runtime.getRuntime().exec(str);
            //p.waitFor();
            p.waitFor();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));

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


            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(output.toString());
            return "Success";
    }

The code executes without error but I do not see file copied at the destination. I also tried to have a single String with the above command instead of having an array but still no success. If I remove /bin/bash then I get error as cannot find cp: no such file or directory .

What am I doing wrong here and how to resolve it?

NOTE: I think that the command is not executed at all as if I for above copy example, even if I give an invalid file location, it does not throw any error and executes like as before without actually executing the command.

UPDATE: I was able to execute cp command by using /bin/cp followed by source and destination. But if I try to execute a command like hadoop fs -put then it does not work. I am trying to execute /usr/bin/hadoop fs -put . I get error as could not find or load main class fs , How do I execute hadoop fs commands ?

cannot find cp: no such file or directory. - means that cp not found. Try to specify full path eg /bin/cp .

The bash command expects a single argument for -c , however you are passing three of them. Try to pass it in same piece, ie {"/bin/bash", "-c", "cp /Users/Desktop/abc.csv /Users/Desktop/folder1/"} .

Alternatively, try some other more concise solution, eg Standard concise way to copy a file in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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