从不在Windows上工作的资源加载图像

时间:2011-06-11 14:10:54

标签: java windows macos path separator

为什么这不适用于Windows,而是使用Mac?

public final static String PATH = "resources" + File.separator;

/** Returns an ImageIcon, or null if the path was invalid. */
public static ImageIcon createImageIcon(String name, String description) {
    java.net.URL imgURL = GuiTools.class.getResource(PATH + name);
    if (imgURL != null) {
        return new ImageIcon(imgURL, description);
    } else {
        System.err.println("Couldn't find file: " + PATH + name);
        return null;
    }
}

1 个答案:

答案 0 :(得分:2)

因为File.separator是文件的系统相关字符,对于mac而言是“/”,对于windows而言是“\”。但是,在URL中,所有分隔符都应为“/”。尝试将第一行更改为:

public final static String PATH = "resources/";