[英]unable to execute terminal command from java code
I want to execute terminal commands,for example cp
, from within the java program. 我想从Java程序中执行终端命令,例如cp
。 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. 我还尝试通过上述命令使用单个String
而不是使用数组,但仍然没有成功。 If I remove /bin/bash
then I get error as cannot find cp: no such file or directory
. 如果删除/bin/bash
则会出现错误,因为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. 更新:我能够通过使用/bin/cp
后跟源和目标来执行cp命令。 But if I try to execute a command like hadoop fs -put then it does not work. 但是,如果我尝试执行类似hadoop fs -put的命令,那么它将无法正常工作。 I am trying to execute /usr/bin/hadoop fs -put
. 我正在尝试执行/usr/bin/hadoop fs -put
。 I get error as could not find or load main class fs
, How do I execute hadoop fs commands ? 由于could not find or load main class fs
出现错误, 如何执行hadoop fs命令 ?
cannot find cp: no such file or directory.
- means that cp not found. -表示找不到cp。 Try to specify full path eg /bin/cp
. 尝试指定完整路径,例如/bin/cp
。
The bash command expects a single argument for -c
, however you are passing three of them. bash命令需要-c
一个参数,但是您要传递三个参数。 Try to pass it in same piece, ie {"/bin/bash", "-c", "cp /Users/Desktop/abc.csv /Users/Desktop/folder1/"}
. 尝试以同一段传递它,即{"/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? 或者,尝试使用其他更简洁的解决方案,例如使用Java复制文件的标准简洁方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.