如何访问SRC文件夹中的文件?

时间:2013-07-21 17:33:02

标签: java image null

您好我一直在尝试从我的SRC文件夹中访问图像文件,以便我可以直接从jar运行它。不幸的是,它没有装载它们,我可以请一些帮助。它是一个空指针异常,无法读取输入文件。这是文件夹的位置以及我在代码中放置的内容。代码:“/ sprites / makeps2.png”目录:C:\ Users \ Lucas \ workspace \ Vigilante \ src \ sprites \ mapsheet2.png如果需要任何额外信息告诉我并生病发送。

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以在.jar存档文件中打包所有必需的资源。并使用

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

可以使用imageIO转换为Image。

答案 2 :(得分:0)

您可以尝试将图像作为ByteArrayInputStream加载到BufferedImage中。像这样的东西:                       BufferedImage img = null;                           尝试{                         BufferedInputStream sc = new BufferedInputStream(ImageLoad.class.getResourceAsStream(file));                     ArrayList in = new ArrayList();                     byte b = null;                     while((b = sc.read)!= null)in.add(b);                     字节[]                     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(例外e){}

然后根据需要使用图片!唯一的事情是你必须将sprites / mapsheet2.png放在与你运行它的类相同的文件夹中。假设您的类是ImageLoad.java,ImageLoad.java必须与sprites / mapsheet2.png位于同一个包中。 EC:

ImageLoad.java在包image.load中,在包image.load中是资源精灵(A Dir)和sprites / mapsheet2.png,并且对于在该区域中加载所需的任何其他图像都是相同的。如果要加载图像并在另一个类中使用它,您可以创建一个包含上述代码的方法,并返回一个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));
                    }
               }