Eseguire comandi o script shell da Java

annuncio pubblicitario
This page was exported from - JPinup
Export date: Thu Jun 1 10:12:51 2017 / +0000 GMT
Eseguire comandi o script shell da Java
Molte volte è utile eseguire dei comandi shell direttamente dal codice java.
La JDK ci offre il metodo exec della classe Runtime, nel package java.lang, che ci permette l'interfacciamento con l'ambiente del
sistema dove l'applicazione è in esecuzione. Il metodo può eseguire uno script oppure una serie di comandi.
Vediamo una classe Java che esegue gli stessi comandi del seguente screenshot:
ShellScript.java
Ho implementato una classe con un metodo statico, che accetta in input la serie di comandi da eseguire. Vediamo l'esempio per
windows.
package it.hpe.spring.roo.listener;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.concurrent.Semaphore;
public class ShellScript {
public static String executeCommand(String... command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
// p.waitFor();
InputStreamReader in = new InputStreamReader(p.getInputStream());
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com
| Page 1/2 |
This page was exported from - JPinup
Export date: Thu Jun 1 10:12:52 2017 / +0000 GMT
BufferedReader reader = new BufferedReader(in);
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "n");
}
p.destroy();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
public static void main(String[] args) {
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/c";
command[2] = "cd \tmp\ && mvn --version";
String result = ShellScript.executeCommand(command);
System.out.println(result);
}
}
L'output è
Apache Maven 2.2.1 (r801777; 2009-08-06 21:16:01+0200)
Java version: 1.7.0_79
Java home: C:Program FilesJavajdk1.7.0_79jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7" version: "6.1" arch: "amd64" Family: "windows"
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com
| Page 2/2 |
Scarica