Reputation: 2991
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?
Upvotes: 2
Views: 292
Reputation: 28991
cannot find cp: no such file or directory.
- means that cp not found. Try to specify full path e.g. /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, i.e. {"/bin/bash", "-c", "cp /Users/Desktop/abc.csv /Users/Desktop/folder1/"}
.
Alternatively, try some other more concise solution, e.g. Standard concise way to copy a file in Java?
Upvotes: 3