That is actually a sort of bad practice to distribute WebDriver.exe
within your java program, since it will stale after the browser will get updated. You also won't be able to run the exe
file straight from the jar
file. However if you have no options I can suggest the following way:
- Put your
exe
file to resources
folder
- Within the code implement copying the file from
resources
to some place in the file system.
- Execute that file from the code
- Build
jar
(exe
file will be placed as a resource
to your jar
)
Below is a simple example on how you can achieve points 2 and 3:
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException, IOException {
// Copy file from resources to file system (path taken from the command line argument)
InputStream is = Main.class.getResourceAsStream("phantomjs.exe");
File exeFile = new File(args[0]);
FileOutputStream fos = new FileOutputStream(exeFile);
byte bytes[] = new byte[1000];
int k = 0;
while((k = is.read(bytes)) != -1){
fos.write(bytes, 0, k);
}
fos.close(); // Do not forget to close the outputstream, otherwise your code will be holding the file and it won't be possible to execute it
// Below is just an example on how you can execute the file after copying
List<String> commands = new ArrayList<String>(); //
commands.add(args[0]); // Start file with argument
commands.add("--help"); //
Process p = new ProcessBuilder().command(commands).start();
InputStream i = p.getInputStream(); //
Scanner scanner = new Scanner(i); //
while (scanner.hasNextLine()){ // Print the output of the file
System.out.println(scanner.nextLine()); //
} //
}
}
In this example we have our phantomjs.exe
file in resource
folder. We also take the destination for the file copying from command line arguments. So the way how to execute the jar
will look like:
java -jar mysuper.jar c:/Temp/pjs.exe