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
To find the installation folder of a program using a desktop shortcut: From your desktop, right-click on the program's shortcut. Click on the Properties, and the Properties window should now be displayed. Click on the Shortcut tab, and you will find the installation path in the Target field.
PATH is an environment variable on Unix-like operating systems, DOS, OS/2, and Microsoft Windows, specifying a set of directories where executable programs are located. In general, each executing process or user session has its own PATH setting.
To stick with a terminal command but do it a lot easier, you can do: "dpkg -s git". You'll get the package details if it's installed or "Package `git' is not installed and no info is available" if it's not installed.
You can use scripts-common to reach your need. To check if something is installed, you can do: checkBin <the_command> || errorMessage "This tool requires <the_command>. Install it please, and then run this tool again."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With