加载具有不同路径的多个图像

时间:2019-04-13 11:42:42

标签: java eclipse

所以我尝试从相同的路径但使用不同的名称加载两个图像。 如果我直接从图像复制路径,一切正常。 但是,如果我尝试从系统构建路径,则只能使用其中之一(img1)。 我尝试了几种在互联网上找到的不同方法来构建路径,但结果是相同的。

什么会导致此问题?

public void loadImages(String nm) {
    File f = null;
    BufferedImage image = null;

    System.out.println("read img:");

    String pathName = PICTURE_PATH + this.getMyColor().toString().toLowerCase() + nm;

    // read successful this img path.
    try {
        f = new File(pathName + "North.png");
        f.canRead();
        System.out.println("\nimg1 path:" + f);
        System.out.print("img1 absolute path:" + f.getAbsolutePath());
        img1 = ImageIO.read(f);
        if (!f.canRead())
            throw new IOException("Cant read the first file");
        if (!f.exists())
            throw new IOException("Cant find the first file");
        System.out.println("Successful read img 1");
    } catch (IOException e) {
        System.out.println("Error:" + e);
    }

    // got here exception error for this img path.
    try {
        f = new File(pathName + "East.png");
        System.out.println("\nimg2 path:" + f);
        System.out.println("img2 absolute path:" + f.getAbsolutePath());
        if (!f.canRead())
            throw new IOException("Cant read the second file");
        if (!f.exists())
            throw new IOException("Cant find the second file");

        img2 = ImageIO.read(f);
        System.out.println("Successful read img 2");
    } catch (IOException e) {
        System.out.println("Error:" + e);
    }
    System.out.println("Done.");
}


//this is the relevant output for this function:
//read img:
img1 path:src\icons\‏‏silverCarNorth.png
img1 absolute path:A:\Tools\eclipse\WorkPlace\HW1\src\icons\‏‏silverCarNorth.png
Successful read img 1

img2 path:src\icons\‏‏silverCarEast.png
img2 absolute path:A:\Tools\eclipse\WorkPlace\HW1\src\icons\‏‏silverCarEast.png
Error:java.io.IOException: Cant read the second file
Done.

1 个答案:

答案 0 :(得分:0)

所以看起来图像上有一些额外的字符。 该网站不支持此类字符,因此我从cmd添加了打印屏幕。 这是来自cmd的日志: cmd logs

所以我不得不重命名文件并使用Windows命令行手动删除多余的字符。 然后一切都很好!