Java - Esecuzione comandi su CLI
Prima o poi può essere utile astrarre un po’ meno dalla macchina e tornare a interfacciarsi con il Sistema Operativo sottostante. Quello che può tornare utile è quindi un metodo per eseguire comandi di sistema dalla VirtualMachine Java. Il seguente è un metodo che ho scritto in fretta e furia, ma che su sistemi UNIX sembra funzionare molto molto bene:
Java |copy code |?
public static String execCommand(String cmd) throws IOException{ |
String result = null; |
BufferedReader stdout = null; |
BufferedReader stderr = null; |
Runtime runtime = null; |
Process proc = null; |
runtime = Runtime.getRuntime(); |
proc = runtime.exec(cmd); |
stderr = new BufferedReader(new InputStreamReader( |
proc.getErrorStream())); |
String temp = stderr.readLine(); |
/*check if errors occurred*/ |
if(temp!=null){ |
do{ |
if(result==null) |
result = temp+"\n"; |
else |
result += temp+"\n"; |
temp = stderr.readLine(); |
}while(temp!=null); |
stderr.close(); |
throw new IOException(result); |
} |
/*if no exceptions occurred then proceed to return the output*/ |
stdout = new BufferedReader(new InputStreamReader( |
proc.getInputStream())); |
temp = stdout.readLine(); |
while(temp!=null){ |
if(result==null) |
result = temp+"\n"; |
else |
result += temp+"\n"; |
temp = stdout.readLine(); |
} |
stdout.close(); |
return result; |
} |
L’idea è semplice: se il comando fallisce, restituisco l’esito del comando (lo standard error) come un’eccezione di I/O, altrimenti il metodo torna l’esito del comando (lo standard output).
A questo punto possiamo, per esempio, scrivere il seguente main, un po’ inutile, ma rende l’idea
Java |copy code |?
February 5th, 2009 at 12:35