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!
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");
You can use:
getClass().getResourceAsStream("/" + fileName);
to get InputStream of file in resources folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With