I have a java program that requires the calling of a C binary to perform some computations.
The way I'm currently doing this is using a ProcessBuilder and running the C program as an external binary.
However, I'd like to migrate this program into the cloud, so I need everything to be in one java project and calling the C program as an external binary would not be possible. Is there some way for me to package the C binary into the jar somehow and call that in my program?
Your binary file can be packaged into a JAR. When your program is running, you can abstract your binary file out of JAR and store it into a temp file, and execute it.
When the JAR is running, its path can be obtained as:
File temp = File.createTempFile("temp_name", "suffix");
temp.deleteOnExit();
InputStream input = YourClass.class.getClassLoader().getResourceAsStream("your_binary_file");
WRITE_INPUTSTREAM_TO_FILE(input, temp);
And now, you got an temp file which can be executed!
Here is a solution, but I don't consider it as a good one. I still think that deploying a C library with JNI interfaces exposed would be a better option.
1. Crete C library with JNI interfaces exposed.
2. Pack the library to a JAR.
3. At run time use ClassLoader.getResourceAsStream to get a stream to your resource
4. Store the stream to a file
5. Use System.load(path-to-file) to load the library
I'm omitting details about JNI - it's a big and separate topic that you should explore yourself.
If you simply want to run an executable, and not to use a C lib, you can skip #1 and #5 above and simply run the executable that you've stored in the file.
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