简体   繁体   English

如何在Linux中通过Java执行Shell脚本并保存为文本文件命令

[英]How to execute shell script and save in text file command through java in linux

I m using Linux. 我正在使用Linux。

I want to call a small executable application from my java command line which is called "wmic". 我想从我的java命令行调用一个小的可执行应用程序,称为“ wmic”。 It needs an input query. 它需要一个输入查询。 Output are stored in text file in the specific directory. 输出存储在特定目录下的文本文件中。

When I use the command in Linux Terminal 当我在Linux Terminal中使用命令时

echo "Hello World" >> /home/kannan/hello.txt

the output is stored in hello.txt file. 输出存储在hello.txt文件中。

but when i call this command from java 但是当我从Java调用此命令时

Process p = Runtime.getRuntime().exec("echo \"Hello World\" >> /home/kannan/hello1.txt");

the output is not created any hello1.txt file 输出未创建任何hello1.txt文件

Please any one help me. 请任何人帮助我。

Thanks in Advance. 提前致谢。

Use a ProcessBuilder . 使用ProcessBuilder It makes it easy to redirect output of a command to file as shown below: 可以很容易地将命令输出重定向到文件,如下所示:

new ProcessBuilder("echo", "hello").redirectOutput(new File("output.txt")).start();

If you want to append to the output file: 如果要附加到输出文件:

new ProcessBuilder("echo", "hello").redirectOutput(Redirect.appendTo(new File("output.txt"))).start();

What you are executing is bash command (echo). 您正在执行的是bash命令(回显)。 Your java program do not work as bash interpreter 您的Java程序不能用作bash解释器

To execute any script which requires bash or shell scripting features, your need to execute that interpreter 要执行任何需要bash或shell脚本功能的脚本,您需要执行该解释器

To solve your problem you can follow below steps 1. Write your string into temp .sh file. 要解决您的问题,您可以按照以下步骤操作:1.将您的字符串写入temp .sh文件。 Lets call it temp.sh 2. execute below using Runtime.getRuntime().exec 让我们称之为temp.sh 2.使用Runtime.getRuntime()。exec在下面执行

Process p = Runtime.getRuntime().exec("bash temp.sh");

bash will try to execute any command in temp.sh bash将尝试在temp.sh中执行任何命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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