Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file from a relative path

Tags:

java

file

io

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!

like image 497
Burak Özmen Avatar asked Dec 06 '25 09:12

Burak Özmen


2 Answers

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");
like image 57
Kedarnath Avatar answered Dec 07 '25 23:12

Kedarnath


You can use:

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

to get InputStream of file in resources folder.

like image 23
pbespechnyi Avatar answered Dec 07 '25 21:12

pbespechnyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!