3

I know this question has been asked like 1000 times before. I did tried all the solutions(How to read file from relative path in Java project? java.io.File cannot find the path specified did not worked also), however none of them seems to be working.

I am trying to read a image file by providing a relative path like this:

BufferedImage image;
image = fm.readMap("..\\..\\resources\\5x5.png");

Reading:

public BufferedImage readMap(String path)
{
    BufferedImage img = null;
    try{
        img = ImageIO.read(new File(path));
    }
    catch (IOException e){
        System.out.println("Image not found.");
        e.printStackTrace
    }

    return img;
}

location of the code :

parent --> src --> externalsourcemanagement --> TestMapAnalysis.java

location of the image : parent --> resources --> 5x5.png

Thanks in advance!

Community
  • 1
  • 1
Burak Özmen
  • 865
  • 2
  • 11
  • 28

3 Answers3

3

Relative path is not relative to the Source (.java) file, it is relative to the classpath. If you have classes under bin folder in the same directory as src, then your relative path of image would be

image = fm.readMap("resources\\5x5.png");
Kedarnath
  • 260
  • 1
  • 3
  • 13
1

You can use:

getClass().getResourceAsStream("/" + fileName);

to get InputStream of file in resources folder.

pbespechnyi
  • 2,251
  • 1
  • 19
  • 29
1

Try changing your location of image like:

src\\resources\\5x5.png

Example Code:

String pathToImageSortBy = "nameOfProject/resources/5x5.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
Sarz
  • 1,970
  • 4
  • 23
  • 43