user2087814
user2087814

Reputation: 9

Running windows commands by java program

I want to run command

ipmsg.exe /MSG 192.168.0.8 "TEXT MESSAGE"

by a java program. Can anybody help me?

I am trying the following lines. But it is not working..

Runtime run_t = Runtime.getRuntime();

Process notify = run_t.exec("cmd /c ipmsg.exe /MSG 192.168.0.8 Hello");

PS:- My computer is connected to the computer with ip address 192.168.0.8 with LAN.

Upvotes: 0

Views: 468

Answers (2)

imxylz
imxylz

Reputation: 7937

You need two threads to capture the standal output or error output like this:

package demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class ExecDemo {

    public static void main(String[] args) throws Exception {

        final Process p = Runtime.getRuntime().exec("nslookup google.com");
        Thread stdout = new Thread() {
            public void run() {
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                try {
                    while ((line = br.readLine())!=null) {
                        System.out.println(line);
                    }
                    br.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        };
        Thread stderr = new Thread() {
            public void run() {
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String line = null;
                try {
                    while ((line = br.readLine())!=null) {
                        System.out.println(line);
                    }
                    br.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

            }
        };
        //
        stdout.start();
        stderr.start();
        //
        stdout.join();
        stderr.join();
        //
        p.waitFor();
    }

}

output (In Mac OS X):

Server:     192.168.6.1
Address:    192.168.6.1#53

Non-authoritative answer:
Name:   google.com
Address: 74.125.31.113
Name:   google.com
Address: 74.125.31.138
Name:   google.com
Address: 74.125.31.139
Name:   google.com
Address: 74.125.31.100
Name:   google.com
Address: 74.125.31.101
Name:   google.com
Address: 74.125.31.102

Upvotes: 1

asgs
asgs

Reputation: 3984

Use a ProcessBuilder for better working with external processes. Also, always pass arguments as separate strings, apart from the command name.

Upvotes: 2

Related Questions