IOException:无法读取输入文件。我无法使用不同的路径找到解决方案,即使是手动



如何解决此错误? 我无法使用不同的路径找到解决方案,即使是手动的。请解释如何使用绝对路径将图像读入缓冲图像。

private BufferedImage[] image = new BufferedImage[9];
private int imageNo = 0;
private Boolean draw = false;
private int drawType;
private String [] realtivePath;
private String [] absolutePath;
//=============================================================================
public DrawPanel() {
    int i,j; 
    absolutePath =  new String[9];
    realtivePath = new String []{"B_Pictures\Burj Khalifa.jpg", "B_Pictures\Taipei 101.jpg", "B_Pictures\Willis Tower.jpg",
        "B_Pictures\Empire State Building.jpg", "B_Pictures\Chrysler Building.jpg",
        "B_Pictures\Woolworth Building.jpg", "B_Pictures\Met Life Tower.jpg",
        "B_Pictures\Singer Building.jpg", "B_Pictures\Philadelphia City Hall.jpg"}; 
    //======================================================================
    for(i = 0;i < 9; i++)
    {
        absolutePath[i] = new File(realtivePath[i]).getAbsolutePath();
        System.out.println("Path is: "+absolutePath[i]);
    }
   //=======================================================================
    try {
        for (j = 0; j < 9; j++) {
            image[j] = ImageIO.read(new File(absolutePath[j])); //<-- can't read absolute path!
        }
    }catch (IOException e) {
        e.printStackTrace();
        //System.out.println("Error reading file");
    }

显然你的绝对路径是不正确的。 您正在根据运行 Java 应用程序的目录解析相对路径。 显然,这些是错误的相对路径(或者您在与预期不同的位置运行应用程序)。

更新:

作为澄清,如果相对路径当前是相对的,File.getAbsolutePath() 会使相对路径成为绝对路径。 这是纯粹的文本更改,并不意味着生成的绝对路径有任何有效性。 例如,如果你有一个相对路径"foo/bar",并且你根据当前目录"/blah"将其设为绝对路径,那么你得到的绝对路径是"/blah/foo/bar"。 这并不意味着"/blah/foo/bar"是一个有效的路径

以下是检查代码的简单方法:

System.out.println("Path is: "+absolutePath[i] + ", isReadable " + new File(absolutePath[i]).canRead());

最新更新