How do I get the path of an image that is inside the folder of my project in JAVA

0

The image is being saved in for example C: \ Users \ abc \ Downloads \ Project \ image.png and within that folder are the subfolders of the project but I need an address that works on all computers, so how do I find the image inside that folder? the image I can not put a folder images and use \ src \ images \ imagen.png or \ images \ imagen.png How do you do it?

    
asked by TK154 09.05.2018 в 07:26
source

2 answers

1

What you are asking is resolved from the class you are running by using your classloader.

Suppose that your project has included in its classpath a folder called doc and in which there is a file called test.pdf . In order to obtain the complete physical route to that resource, you must execute the following:

<instanciadetuclase>.getClass().getClassLoader().getResource("doc/test.pdf");

You can also get the same with

<nombredetuclase>.class.getClassLoader().getResource("doc/test.pdf");

If instead of using getResource () you use getResourceAsStream () you will already have an InputStream to directly read the contents of that file.

Finally, a couple of details to keep in mind:

  • getClass (). getClassLoader (). getResource (), find the path you specify as a parameter from the root of the folder where all the binaries are
  • getClass (). getResource () is very similar, but it looks for the last route from the path where the class that is making the invocation is.

Using the example above, assuming the class that executes the code is in a packet, these two calls would return the same result:

<instanciadetuclase>.getClass().getClassLoader().getResource("doc/test.pdf");
<instanciadetuclase>.getClass().getResource("/doc/test.pdf");

I hope I have helped you.

    
answered by 09.05.2018 в 12:33
0

In your project create a folder to put the images and with the help of the relative routes you can access the image ../yourfolder/name of the image, when generating the jar this folder will be included and can be accessible from any computer

    
answered by 09.05.2018 в 16:41