viernes, 6 de agosto de 2010

Ejecutando comandos WIN/DOS en Java

Aquí va un código sencillo para ejecutar comandos de DOS en Java:


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

public class DosCommandExecutor {

public static String exec(String command) {
String cmdOutput = "";
try {
Process p = Runtime.getRuntime().exec( "cmd /c " + command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = null;

while ((s = stdInput.readLine()) != null) {
cmdOutput += s + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
return cmdOutput;
}

public static void main(String[] args) {
System.out.println( DosCommandExecutor.exec("dir") );
}
}

Salida:


Volume in drive C is OSDisk
Volume Serial Number is 901D-8590

Directory of C:\code

08/03/2010 01:57 PM <DIR> .
08/03/2010 01:57 PM <DIR> ..
07/30/2010 12:14 PM 301 .classpath
07/30/2010 12:14 PM 388 .project
07/30/2010 12:14 PM <DIR> .settings
08/03/2010 02:00 PM <DIR> back_up
08/06/2010 01:57 PM <DIR> bin
08/06/2010 01:57 PM <DIR> src
2 File(s) 689 bytes
6 Dir(s) 5,739,667,456 bytes free

No hay comentarios:

Publicar un comentario