Skip to content
Advertisement

How to check existence of a program in the path

I’m writing a program in scala which call:

Runtime.getRuntime().exec( "svn ..." )

I want to check if “svn” is available from the commandline (ie. it is reachable in the PATH). How can I do this ?

PS: My program is designed to be run on windows

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement