how to run a command at terminal from java program?

前端 未结 6 2159
孤城傲影
孤城傲影 2020-11-29 03:14

I need to run a command at terminal in Fedora 16 from a JAVA program. I tried using

Runtime.getRuntime().exec(\"xterm\"); 

but this just op

6条回答
  •  青春惊慌失措
    2020-11-29 03:55

    I vote for Karthik T's answer. you don't need to open a terminal to run commands.

    For example,

    // file: RunShellCommandFromJava.java
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class RunShellCommandFromJava {
    
        public static void main(String[] args) {
    
            String command = "ping -c 3 www.google.com";
    
            Process proc = Runtime.getRuntime().exec(command);
    
            // Read the output
    
            BufferedReader reader =  
                  new BufferedReader(new InputStreamReader(proc.getInputStream()));
    
            String line = "";
            while((line = reader.readLine()) != null) {
                System.out.print(line + "\n");
            }
    
            proc.waitFor();   
    
        }
    } 
    

    The output:

    $ javac RunShellCommandFromJava.java
    $ java RunShellCommandFromJava
    PING http://google.com (123.125.81.12): 56 data bytes
    64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
    64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
    64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms
    
    --- http://google.com ping statistics ---
    3 packets transmitted, 3 packets received, 0.0% packet loss
    round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms
    

提交回复
热议问题