Reading a file from a relative path

I know this question has been asked 1000 times before. I've tried all solutions ( How do I read a file from a relative path in a Java project? Java.io.File can't find the path specified) doesn't work either) however none seem to work.

I am trying to read an 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;
}

      

code location:

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

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

Thanks in advance!

+3


source to share


3 answers


The relative path does not refer to the source (.java) file, it refers to the classpath. If you have classes under bin folder in the same directory as src then your image relative path will be



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

      

+3


source


You can use:

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

      



to get the InputStream

file in the resources folder.

+1


source


Try changing the location of the image, for example:

src\\resources\\5x5.png

      

Sample code:

String pathToImageSortBy = "nameOfProject/resources/5x5.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

      

+1


source







All Articles