Hello folks!
I have a problem in my code. I want to read image files from within a Jar, or to be more precise, I want to count them.
I can load images from the loadImage() method I have created, looks like this:
@Override
public Image loadImage(String path) throws IOException{
if(Mothership.infoActive()){System.out.println("Loading image: " + path);}
Image tempImg;
try{
tempImg = new ImageIcon(getClass().getResource(path)).getImage();
if(tempImg != null){
if(Mothership.infoActive()){System.out.println("Image " + path + " loaded without errors");}
return tempImg;
}else{
return null;
}
}catch(NullPointerException assfuck){
throw new IOException();
}
}
Now, I want to scan the folders inside the jar file to see how many images are in there so that I can build my program to adapt itself to how many images there are in each folder. I found this piece of code on stack overflow which does the trick, but with one small problem. It won’t let me run the program inside eclipse, it doesn’t find the images if they are not packed in a Jar. I am not very good at file IO so help and advice would be greatly appreciated
public class Main {
String[] lol;
CodeSource src = Main.class.getProtectionDomain().getCodeSource();
List<String> list = new ArrayList<String>();
public static void main(String[] args){
Main m = new Main();
m.init();
}
public void init(){
try {
read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void read() throws IOException{
if(src != null){
System.out.println("Check");
URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream( jar.openStream());
ZipEntry ze = null;
while((ze = zip.getNextEntry()) != null){
String entryName = ze.getName();
if(entryName.endsWith(".png") || entryName.endsWith(".PNG") ) {
list.add(entryName );
System.out.println(entryName);
}
}
}
lol = list.toArray( new String[ list.size() ] );
System.out.println(lol.length);
}
}