简体   繁体   中英

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;
    }
}

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());

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM