este código usa el comando "where" en Windows, y el comando "which" en otros sistemas, para verificar si el sistema conoce el programa deseado en PATH. Si se encuentra, la función devuelve un java.nio.file.Path para el programa, y null de lo contrario.
Lo probé con Java 8 en Windows 7 y Linux Mint 17.3.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;
public class SimulationUtils
{
private final static Logger LOGGER = Logger.getLogger(SimulationUtils.class.getName());
public static Path lookForProgramInPath(String desiredProgram) {
ProcessBuilder pb = new ProcessBuilder(isWindows() ? "where" : "which", desiredProgram);
Path foundProgram = null;
try {
Process proc = pb.start();
int errCode = proc.waitFor();
if (errCode == 0) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
foundProgram = Paths.get(reader.readLine());
}
LOGGER.info(desiredProgram + " has been found at : " + foundProgram);
} else {
LOGGER.warning(desiredProgram + " not in PATH");
}
} catch (IOException | InterruptedException ex) {
LOGGER.warning("Something went wrong while searching for " + desiredProgram);
}
return foundProgram;
}
private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("windows");
}
}
Para usarlo:
System.out.println(SimulationUtils.lookForProgramInPath("notepad"));
En mi sistema Windows 7, se muestra:
C: \ Windows \ System32 \ notepad.exe
Y en linux:
System.out.println(SimulationUtils.lookForProgramInPath("psql"));
/usr/bin/psql
La ventaja de este método es que debería funcionar en cualquier plataforma y no hay necesidad de analizar la variable de entorno PATH o mirar en el registro. El programa deseado nunca se llama, incluso si se encuentra. Finalmente, no hay necesidad de saber la extensión del programa. gnuplot.exe bajo Windows y en Linux sería gnuplot tanto ser encontrado por el mismo código:
SimulationUtils.lookForProgramInPath("gnuplot")
Las sugerencias para mejorar son bienvenidos!
Creo que sería mejor que hacer "que svn" en lugar de "ayuda SVN". Todavía dará el código de retorno adecuado para determinar si svn existe o no en la ruta, pero en caso de éxito también obtendrá la ruta completa al ejecutable svn. – Apreche
"which" no es un comando de Windows. – EMMERICH
"donde" es el equivalente de Windows de "que" –