0

I m using Linux.

I want to call a small executable application from my java command line which is called "wmic". It needs an input query. Output are stored in text file in the specific directory.

When I use the command in Linux Terminal

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

the output is stored in hello.txt file.

but when i call this command from java

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

the output is not created any hello1.txt file

Please any one help me.

Thanks in Advance.

2 Answers 2

3

Use a 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();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks dudes. but i got another one problem, new ProcessBuilder("wmic", "-U [username]%[password] //[ip_address] \"Select * from Win32_NTLogEvent where LogFile = 'System' and SourceName = 'Microsoft-Windows-DHCPv6-Client' or SourceName = 'Microsoft-Windows-Dhcp-Client'\"").redirectOutput(new File("DHCP.txt")).start(); This query will returned... only USAGE: ... of wmic query. Please help me...
How to convert the below query... wmic -U [username]%[password] //[password] "Select * from Win32_NTLogEvent where LogFile = 'System' and SourceName = 'Microsoft-Windows-DHCPv6-Client' or SourceName = 'Microsoft-Windows-Dhcp-Client'" >> out.txt . Please help dogbane. i am used this query in your format but it will returned usage of wmic.
Try passing each argument of your command as a separate argument in the ProcessBuilder, like this: new ProcessBuilder("wmic", "-U", "[username]%[password]", "//[password]", "Select * from Win32_NTLogEvent where LogFile = 'System' and SourceName = 'Microsoft-Windows-DHCPv6-Client' or SourceName = 'Microsoft-Windows-Dhcp-Client'")
2

What you are executing is bash command (echo). Your java program do not work as bash interpreter

To execute any script which requires bash or shell scripting features, your need to execute that interpreter

To solve your problem you can follow below steps 1. Write your string into temp .sh file. Lets call it temp.sh 2. execute below using Runtime.getRuntime().exec

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

bash will try to execute any command in temp.sh

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.