I made a simple utility app. In it I had an exe file to be run. I got it to run by using:
Runtime.getRuntime().exec(this.getClass().getResource("filename.exe").getPath());
I works perfectly when I run the program from the ide(Netbeans).
But when I try to run the exe using the above command after building(ie from the jar created on building) it does not work at all.
I also tried running this :
Desktop.getDesktop().open(new File("filename.exe"))
but no use again.
Please help
Tried with a usecase, found that getResource search for path "file:/path/to/thejar.jar!filename.exe", and is unable to use the exe inside the jar.
Tried modifying classpath, but failed.
Refered to spring's strategy, which reads config files in jar with an URL connection,
I think the solution can be :
get an InputStream with getResourceAsStream
copy the exe form inside the jar to a temp file with the ImputStream
run the temp exe file located outside the jar.
This works (OK when compiled to jar, but NOK in IDE, 'cause "getResource" search at different place):
package me.mren.loadresource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class Runner {
/**
* @param args
*/
public static void main(String[] args) {
try {
String filename = "/resources/filename.exe";
System.out.println(Runner.class.getResource(filename));
InputStream fi = Runner.class.getResourceAsStream(filename);
File temp = File.createTempFile("temp_exe", "");
System.out.println(temp.getPath());
OutputStream fo = new FileOutputStream(temp);
byte[] b = new byte[1024];
int count = 0;
while ((count = fi.read(b)) != -1) {
fo.write(b, 0, count);
}
fi.close();
fo.close();
System.out.println(temp.canExecute());
Runtime.getRuntime().exec(temp.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Project's files structure:
C:\USERS\REN MIN\DEV ENV\JAVA\WORKSPACE\LOADRESOURCE
│ .classpath
│ .project
│ pom.xml
│
├─.settings
│ org.eclipse.jdt.core.prefs
│ org.eclipse.m2e.core.prefs
│
├─src
│ ├─main
│ │ ├─java
│ │ │ └─me
│ │ │ └─mren
│ │ │ └─loadresource
│ │ │ Runner.java
│ │ │
│ │ └─resources
│ │ filename.exe
│ │
│ └─test
│ ├─java
│ └─resources
└─target
│ loadresource-0.0.1-SNAPSHOT.jar
│
├─classes
│ │ filename.exe
│ │
│ └─me
│ └─mren
│ └─loadresource
│ Runner.class
│
├─maven-archiver
│ pom.properties
│
├─surefire
└─test-classes
the file structure inside the jar:
E:\TEST\RESULT
│ .classpath
│ .project
│ pom.xml
│
├─me
│ └─mren
│ └─loadresource
│ Runner.class
│
├─META-INF
│ MANIFEST.MF
│
└─resources
filename.exe