2011-08-18 15 views
32

In Java, voglio essere in grado di eseguire un comando di Windows.Come eseguire comandi Windows utilizzando Java - Modifica impostazioni di rete

Il comando in questione è netsh. Questo mi consentirà di impostare/ripristinare il mio indirizzo IP.

Nota che non voglio eseguire un file batch.

Invece di utilizzare un file batch, voglio eseguire direttamente tali comandi. È possibile?


Ecco il mio implementato la soluzione per il futuro di riferimento:

public class JavaRunCommand { 
    private static final String CMD = 
     "netsh int ip set address name = \"Local Area Connection\" source = static addr = 192.168.222.3 mask = 255.255.255.0"; 
    public static void main(String args[]) { 

     try { 
      // Run "netsh" Windows command 
      Process process = Runtime.getRuntime().exec(CMD); 

      // Get input streams 
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); 
      BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); 

      // Read command standard output 
      String s; 
      System.out.println("Standard output: "); 
      while ((s = stdInput.readLine()) != null) { 
       System.out.println(s); 
      } 

      // Read command errors 
      System.out.println("Standard error: "); 
      while ((s = stdError.readLine()) != null) { 
       System.out.println(s); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(System.err); 
     } 
    } 
} 
+1

Questo è stato risposto così tante volte. Basta guardare i suggerimenti StackOverflow per trovare alcuni di loro – SJuan76

+0

@ SJuan76, le mie scuse. Potrebbe forse mi collegare ad alcune di queste domande? – mre

+1

@mre Basta guardare nella barra laterale. –

risposta

25
Runtime.getRuntime().exec("netsh"); 

Vedere Runtime Javadoc.

MODIFICA: una risposta successiva di leet suggerisce che questo processo è ora deprecato. Tuttavia, come da commento di DJViking, questo non sembra essere il caso: Java 8 documentation. Il metodo non è deprecato.

+2

Nel mio ambiente nment, dovevo anteporre il comando a "cmd/c", ad es. 'Runtime.getRuntime(). exec (" cmd/c netsh ");' – Daniel

2
public static void main(String[] args) { 
    String command="netstat"; 
    try { 
     Process process = Runtime.getRuntime().exec(command); 
     System.out.println("the output stream is "+process.getOutputStream()); 
     BufferedReader reader=new BufferedReader(new InputStreamReader(process.getInputStream())); 
     String s; 
     while ((s = reader.readLine()) != null){ 
      System.out.println("The inout stream is " + s); 
     }     
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

Questo funziona.

+1

Questo legge ogni altra riga dell'output. dovrebbe essere: 'String s; while ((s = reader.readLine()! = Null) { System.out.println (s); } ' –

+0

' while ((s = reader.readLine())! = Null) {'è corretto – SuB

26

Usa ProcessBuilder

ProcessBuilder pb=new ProcessBuilder(command); 
pb.redirectErrorStream(true); 
Process process=pb.start(); 
BufferedReader inStreamReader = new BufferedReader(
    new InputStreamReader(process.getInputStream())); 

while(inStreamReader.readLine() != null){ 
    //do something with commandline output. 
} 
+5

Qual è la base per questa conclusione? Esaminando la javadoc, non viene dichiarato deprecato. https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#exec -java.lang.String- – DJViking

+0

Aggiornamento di questo: Poiché questa domanda è usata come riferimento quando si segnalano i duplicati (cioè puntiamo i duplicati a questa pagina), sarebbe bello chiarire questa risposta, che ha più upvotes che l'accettato risposta C'è una fonte per queste informazioni? Se no, forse dovrebbe essere rimosso come risposta strizzare? – Nathan

+2

'Runtime.getRuntime(). exec()' non è deprecato. – Daniel

0

È possibile eseguire il comando con Runtime.getRuntime().exec("tree");. Ma questo eseguirà solo eseguibili trovati nel percorso, non comandi come echo, del, ... Ma solo cose come tree.com, netstat.com, ... Per eseguire comandi regolari, dovrai mettere cmd /c prima del comando (unxmple: Runtime.getRuntime().exec("cmd /c echo echo");

Problemi correlati