简体   繁体   中英

How can I access files in my SRC folder?

Hi ive been trying to access image files from within my SRC folder so that I can run it directly from the jar. Unfortunatly its not loading them can I please have some help. Its a null pointer exception and cannot read input file. here is the location of the folder and what I put in the code. CODE: "/sprites/mapsheet2.png" Directory: C:\\Users\\Lucas\\workspace\\Vigilante\\src\\sprites\\mapsheet2.png if any extra info is needed tell me and ill send it.

.jar文件中的资源可以加载: getClass().getResource()它返回具有正确路径的URL

Image icon = ImageIO.read(getClass().getResource("image´s path"));

You can pack all required resources at the .jar archive file. And access it using

InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("res\file.img")

can use imageIO for converting to Image.

You could try to load the image as a ByteArrayInputStream, into a BufferedImage. Something like this: BufferedImage img = null; try{ BufferedInputStream sc = new BufferedInputStream(ImageLoad.class.getResourceAsStream(file)); ArrayList in = new ArrayList(); byte b = null; while((b = sc.read) != null)in.add(b); byte[] bytes = new byte[in.size()];
for(int i = 0; i < in.size(); i ++)bytes[i] = in.get(i); img = ImageIO.read(new ByteArrayInputStream(bytes)); }catch(Exception e){}

and then just use the image as you need it! The only thing is you have to have sprites/mapsheet2.png in the same folder as the class you are running it from. Say your class is ImageLoad.java, ImageLoad.java would have to be in the same package as sprites/mapsheet2.png. EC:

ImageLoad.java is in package image.load, in package image.load are the resources sprites(A Dir), and sprites/mapsheet2.png, and the same for any other images required to load in that area. If you want to load the image and use it in another class, you could just create a method including the above code, and return a bufferedImage. EC:

    public class ImageLoad {
       public static BufferedImage load(String file) throws Exception{
                BufferedInputStream sc = new BufferedInputStream(ImageLoad.class.getResourceAsStream(file));
                ArrayList<Byte> in = new ArrayList<Byte>();
                byte b = null;
                while((b = sc.read) != null)in.add(b);
                byte[]
                bytes = new byte[in.size()];                    
                for(int i = 0; i < in.size(); i ++)bytes[i] = in.get(i);
                return ImageIO.read(new ByteArrayInputStream(bytes));
                    }
               }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM