How to check existence of a program in the path
Here's a Java 8 solution:
String exec = <executable name>;
boolean existsInPath = Stream.of(System.getenv("PATH").split(Pattern.quote(File.pathSeparator)))
.map(Paths::get)
.anyMatch(path -> Files.exists(path.resolve(exec)));
Replace anyMatch(...)
with filter(...).findFirst()
to get a fully qualified path.
Here's a cross-platform static method that compares common executable extensions:
import java.io.File;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static java.io.File.pathSeparator;
import static java.nio.file.Files.isExecutable;
import static java.lang.System.getenv;
import static java.util.regex.Pattern.quote;
public static boolean canExecute( final String exe ) {
final var paths = getenv( "PATH" ).split( quote( pathSeparator ) );
return Stream.of( paths ).map( Paths::get ).anyMatch(
path -> {
final var p = path.resolve( exe );
var found = false;
for( final var extension : EXTENSIONS ) {
if( isExecutable( Path.of( p.toString() + extension ) ) ) {
found = true;
break;
}
}
return found;
}
);
}
This should address most of the critiques for the first solution. Aside, iterating over the PATHEXT
system environment variable would avoid hard-coding extensions, but comes with its own drawbacks.
I'm no scala programmer, but what I would do in any language, is to execute something like 'svn help
' just to check the return code (0 or 1) of the exec method... if it fails the svn is not in the path :P
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("svn help");
int exitVal = proc.exitValue();
By convention, the value 0 indicates normal termination.