获取资源路径

时间:2010-06-29 11:01:29

标签: java path

在eclipse中创建了一个包含所有图像的新文件夹“resources”。我将此文件夹添加到类路径中。

现在我尝试访问此图片

URL url = new URL("imageA");

我也试过

URL url = new URL("resources/imageA");

两者都不起作用。有什么问题?

此致 基督教

4 个答案:

答案 0 :(得分:3)

如果你从类路径加载,你应该做这样的事情

InputSteam is =  this.getClass().getClassLoader().getResourceAsStream("resources/myimage.png")

答案 1 :(得分:1)

答案 2 :(得分:1)

有关路线,请参阅here。您无法直接使用网址加载图片(实际上您可以,但这很复杂,请参阅this question

实际上你需要做这样的事情:

ClassLoader loader = ClassLoader.getSystemClassLoader();

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

答案 3 :(得分:1)

如果您尝试从本地位置加载图像,则可以使用此类内容。

File file = new File("D:/project/resources/imageA.jpg");
Image image = ImageIO.read(file);

如果您打算从网址阅读图片,请使用以下代码:

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