What I’m trying to do is to create a runnable .jar file from java. What I do is I fill the .jar file with resources, then I copy my .class files and the manifest file from another .jar file.
However, when I start the newly created .jar file, it starts up as normal. However, all calls to MyClass.class.getResource() always return null.
I have opened the .jar file with winrar and confirmed that the resources exist (they do indeed exist).
So my problem is basically that MyClass.class.getResource() can’t find any resources even though they exist.
Here is the code I use to create the .jar file.
//This function build to the project to the specified file
public void buildProject(File file) {
if (file == null)return;
try {
JarOutputStream out = new JarOutputStream(new FileOutputStream(file), new JarFile(GenericMethods.getHome()).getManifest());
//First copy all src-files
insert(new File("src/"), out);
//Now copy the class files from this jar
File jarfile = new File(GenericMethods.getHome());
if(!jarfile.isDirectory()) insertFromJAR(out, jarfile);
out.close();
} catch (IOException ex) {
Logger.getLogger(ProjectBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}
//@input File f is the file that will be inserted
//@input JarOutputStream out is the ouputstream connected to a jar file.
public void insert(File f, JarOutputStream out) {
if(f.isDirectory()) {
File[] files = f.listFiles();
for(File file:files)insert(file, out);
}else {
byte[] buf = new byte[1024];
try {
InputStream in = new BufferedInputStream(new FileInputStream(f));
String path = f.getPath();
if(path.startsWith("src"))path = path.replaceFirst("src", "").substring(1);
out.putNextEntry(new JarEntry(path));
int len;
while((len=in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
} catch (IOException ex) {
Logger.getLogger(ProjectBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void insertFromJAR(JarOutputStream out, File jarFile) {
try {
JarFile jf = new JarFile(jarFile);
//Get the enumerations from the zipfile
Enumeration enums = jf.entries();
byte[] buf = new byte[1024];
//Loop until the enumeration has no more elements
while(enums.hasMoreElements()) {
//Get the next entry
JarEntry entry = (JarEntry) enums.nextElement();
//Check if the entryname starts with the folder name
if(entry.getName().startsWith("Game")) {
InputStream in = jf.getInputStream(entry);
String path = entry.getName();
out.putNextEntry(new JarEntry(path));
int len;
while((len=in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
}
} catch (IOException ex) {
Logger.getLogger(ProjectBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}