获取资源路径

5

我在Eclipse中创建了一个名为“resources”的新文件夹,并将我的所有图片放在其中。我将此文件夹添加到类路径中。

现在我尝试访问这些图片。

URL url = new URL("imageA");

我也尝试过。
URL url = new URL("resources/imageA");

两个都不起作用。出了什么问题?

真诚地 克里斯蒂安


这个解决方案对我有效:https://dev59.com/nG855IYBdhLWcg3wg0nC#50387930 - Taras Melnyk
4个回答

3
如果您正在从类路径加载,应该像这样操作:
InputSteam is =  this.getClass().getClassLoader().getResourceAsStream("resources/myimage.png")

1

请查看这里获取指导。您无法直接使用URL加载图像(实际上可以,但是比较复杂,请参见此问题)。

实际上,您需要执行类似于以下操作:

ClassLoader loader = ClassLoader.getSystemClassLoader();

if(loader != null) {
   URL url = loader.getResource(name);
}


1
如果您想从本地位置加载图像,可以使用类似于这样的内容。
File file = new File("D:/project/resources/imageA.jpg");
Image image = ImageIO.read(file);

如果您计划从URL读取图像,请使用以下代码:

URL url = new URL("http://www.google.co.in/images/srpr/logo3w.png");
Image image = ImageIO.read(url);

请查看以下代码以更好地理解:
package com.stack.overflow.works.main;

import java.awt.Image;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * @author sarath_sivan
 */

public class ImageLoader {

    private ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    private Image image = null;
    private URL url = null;

    /**
     * Loading image from a URL with the help of java.net.URL class.
     */
    public void loadFromURL() {
        image = null;
        try {
            url = new URL("http://www.google.co.in/images/srpr/logo3w.png");
            if (url != null) {
                image = ImageIO.read(url);
            }

        } catch(Exception exception) {
            exception.printStackTrace();
        }
        display(image, "Loading image from URL...");

    }

    /**
     * Loading image from your local hard-drive with getResource().
     * Make sure that your resource folder which contains the image
     * is available in your class path.
     */
    public void loadFromLocalFile() {
        image = null;
        try {
            url = classLoader.getResource("images.jpg");
            if (url != null) {
                image = ImageIO.read(url);
            }

        } catch(Exception exception) {
            exception.printStackTrace();
        }
        display(image, "Loading image from Local File...");
    }



    private void display(Image image, String message) {
        JFrame frame = new JFrame(message);
        frame.setSize(300, 300);
        JLabel label = new JLabel(new ImageIcon(image));
        frame.add(label);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        ImageLoader imageLoader = new ImageLoader();
        imageLoader.loadFromURL();
        imageLoader.loadFromLocalFile();
    }

}

输出

enter image description here

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接