Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, check if an executable exists in PATH environment [duplicate]

I can print the path using System.getenv("PATH"). Then I probably can traverse those paths and use File to check if the file is exist.

Is there any faster way in Java ?

like image 229
w00d Avatar asked Mar 20 '13 12:03

w00d


3 Answers

You can use Runtime.getRuntime().exec("command"); in try ... catch section. If app won't be in PATH you will get an exception.

[EDIT]

But .. this will execute app instead of check. Sorry.

like image 190
pepuch Avatar answered Nov 15 '22 10:11

pepuch


Is there any faster way in Java ?

In terms of performance, no.

In terms of coding effort, probably no. Certainly I'm not aware of any 3rd-party Java library that will search the command search path to see if an executable exists.

Unfortunately searching for an executable on Windows is a little tricky because you have to account for the various types of executable ... based on file suffixes. Even on Linux / Unix you need to use the new Java 7 file attributes APIs to determine if a candidate file has the execute permissions set.

(I am aware that some commands can be run in ways that are harmless; e.g. they may support an option / argument that outputs a version string, or some help info. However, that only works in specific cases. I'm also aware that on Unix / Linux, there is a built-in shell command called "whereis" that can tell you if an executable command with a given name exists on the search path.)

like image 33
Stephen C Avatar answered Nov 15 '22 10:11

Stephen C


Your approach will work.

I suggest using the File.listFiles(FileFilter filter) method on each directory in the path. This will make searching each directory simpler.

like image 3
Colin D Avatar answered Nov 15 '22 10:11

Colin D