JaminB
JaminB

Reputation: 788

How do I run an executable from a relative path in Java

I am using the following code to execute a .Net compiled executable and store the output. I want to be able to put the .exe in another package and run it. However whenever I try to run my code it tells me the file is not found as a result of me not putting the full path to the file. Is there an easy way to get around this, like include it in the classpath or something that I am missing.

public class ActiveDirectoryQuery {
    private String email = "";
    public ActiveDirectoryQuery(){}


    public void setEmail(String host){
        this.email = host;
    }

    public String getEmail(){
        return this.email;
    }
    public String getUserName() throws IOException{
        Process process = new ProcessBuilder(
        "/relative/path/to/EmailFQDN.exe", this.email).start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        String fullOutput= "";
        while ((line = br.readLine()) != null) {
         System.out.println(line);
         fullOutput=fullOutput+line+"\n";
        }
        return fullOutput;
    }
}

Upvotes: 0

Views: 3993

Answers (3)

D. Moore
D. Moore

Reputation: 124

If the exe file is in the same package as the class file, you can do something like:

ActiveDirectoryQuery.class.getResource("/EmailFQDN.exe").getFile()

to get the path of that file.

Upvotes: 1

matt helliwell
matt helliwell

Reputation: 2678

The path in process builder is nothing to do with the classpath or packages. It is just expecting the exe to be in a directory which you specify.

If you are using a relative path then you need to specify the path relative to the current working directory of the java process. If you are running this from the command line, then it will be whatever directory you were in when you started the process.

Also remember get rid of the leading slash on the directory if you want it to be a relative path.

Upvotes: 0

leonbloy
leonbloy

Reputation: 76016

If the location is relative to the class file (that's you say in the comments; but... are you sure? that's rather unusual), try to get the absolute path via:

URL exe = ActiveDirectoryQuery.class.getResource("relative/path/to/EmailFQDN.exe");
File exefile = new File(exe.getPath());

Upvotes: 1

Related Questions