Java project resource path

How do I add a resources folder to my Java project in Eclipse

I want to have a place to store my image files to use in my Java project (a really simple class that just loads an image onto a panel). I have looked everywhere and cannot find how to do this. How do I do this? I have tried adding a new folder to the project, adding a new class folder to the project, and adding a new source folder to the project. No matter what I do, I always get a IOException . The folders always say they are on the build path, so I’m not sure what to do.

import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; public class PracticeFrame extends JFrame < private static BufferedImage image; Thread thread; public PracticeFrame() < super(); setPreferredSize(new Dimension(640,480)); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); >public static void main (String[] args) < PracticeFrame pframe = new PracticeFrame(); try < image = ImageIO.read(new File("/islands.png")); >catch (IOException e) < e.printStackTrace(); >JPanel panel = new JPanel() < @Override protected void paintComponent(Graphics g) < super.paintComponent(g); g.drawImage(image,0,0,null); >>; panel.setBackground(Color.BLUE); panel.repaint(); pframe.add(panel); > > 

EDIT: Something that worked for me, and I have no idea why, was adding the main/res/ folder as a class folder and then removing it. I ran it while the /main/res/ was part of the build path as a class folder and it still didn’t work. When i added it, i got a popup that told me something about excluded filters. But when i removed the folder from the libraries in the build path, and changed my file path to:

image = ImageIO.read(new File("src/main/res/islands.png")); 

I at least stopped getting the IOException thrown. I must not be adding the image to the panel correctly, because it’s not showing up, but at least it found the file (I think).

Читайте также:  Php сохранение сессии при авторизации

Источник

How do I get the path of a resource when using Maven?

My resources are in C:/Users/Charles/Workspace/ProjectName/src/main/resources Does anyone know why this is happening? Edit:
I suppose I should have mentioned that the path is being used in a library to load resources, but is failing.

I’m sorry, I guess I should have mentioned. My program is failing to load my resources when I give it that path.

3 Answers 3

That is where your compiled code is put when you use maven to build your project. Your resources are being copied to the target/classes folder as part of the build process.

If you then deploy your application to another location, you will find that your code will return the new path to the resource.

As per your comment, try using the following to load your resource:

InputStream resourceStream = myStaticClass.class.getClassLoader().getResourceAsStream("en-us"); 

This uses the current class’s class loader to locate and provide an InputStream to your resource.

When you run mvn compile , one of the steps along the way is to copy your resources directory to the target/classes directory. Now usually if you call myStaticClass.class.getResource , the path you pass in will have target/classes as the root. So lets say you have a file at src/main/resources/my.file.txt You will be able to get it by calling myStaticClass.class.getResource(«/my.file.txt»);

The thing you’re probably forgetting is the «/» there. Without that «/», it will look relative to your class’ directory.

Alternatively, you could do this: ClassLoader.getSystemClassLoader().getResource(«my.file.txt»).getPath() . Notice the lack of a slash.

You are asking why this is happening and you are saying you want to load the resources.

The «why»: see the other posts. No reason to duplicate them here.

The «how»: the following code shows how to load the resources. Assuming they are in a file called «your.resources» and that this file is in the classpath; which, according to your post, it is.

import java.io.IOException; import java.util.Properties; public class Test < public Test() throws IOException < final Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("your.resources")); System.out.println(properties); >public static void main(String[] args) throws IOException < new Test(); >> 

Note that you don’t need to provide the full path of the resources. As long as they are in the classpath, this will find them.

Источник

open resource with relative path in Java

in order to get the real path, but this way does not work. I have no idea which path to use for the directory.

class.getClass() is not the same as class.getClassLoader(). There is another solution too, getResourceAsStream() using a class in the same package as your resource. For more details: tshikatshikaaa.blogspot.nl/2012/07/….

13 Answers 13

I had problems with using the getClass().getResource(«filename.txt») method. Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with ‘/’ . The recommended strategy is to put your resource files under a «resources» folder in the root directory. So for example if you have the structure:

then you can add a resources folder as recommended by maven in:

furthermore you can add subfolders in the resources folder

src/main/resources/textfiles 

and say that your file is called myfile.txt so you have

src/main/resources/textfiles/myfile.txt 

Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package , and you want to access the myfile.txt file from your resource folder. Some say you need to give the:

"/main/resources/textfiles/myfile.txt" path 
"/resources/textfiles/myfile.txt" 

both of these are wrong. After I ran mvn clean compile , the files and folders are copied in the:

folder. But the resources folder is not there, just the folders in the resources folder. So you have:

myapp/target/classes/textfiles/myfile.txt myapp/target/classes/com/mycompany/myapp/* 

so the correct path to give to the getClass().getResource(«») method is:

getClass().getResource("/textfiles/myfile.txt") 

This will no longer return null, but will return your class. It is strange to me, that the «resources» folder is not copied as well, but only the subfolders and files directly in the «resources» folder. It would seem logical to me that the «resources» folder would also be found under `»myapp/target/classes»

@Ava, sure it’s late answer for you, but may help someone. You need to execute mvn clean test-compile command, as it goes after compile in Maven lifecycle. That will generate target/test-classes .

Supply the path relative to the classloader, not the class you’re getting the loader from. For instance:

resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString(); 

In the hopes of providing additional information for those who don’t pick this up as quickly as others, I’d like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):

Project/ src/ // application source code org/ myproject/ MyClass.java test/ // unit tests res/ // resources images/ // PNG images for icons my-image.png xml/ // XSD files for validating XML files with JAXB my-schema.xsd conf/ // default .conf file for Log4j log4j.conf lib/ // libraries added to build-path via project settings

I was having issues loading my resources from the res directory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the res directory to the build-path and then access the resource via:

static final ClassLoader loader = MyClass.class.getClassLoader(); // in some function loader.getResource("images/my-image.png"); loader.getResource("xml/my-schema.xsd"); loader.getResource("conf/log4j.conf"); 

NOTE: The / is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String) instead of Class.getResource(String).

Источник

How to get absolute path to file in /resources folder of your project

Assume standard maven setup. Say in your resources folder you have a file abc . In Java, how can I get absolute path to the file please?

There are three variants of solution, depending on the situation: stackoverflow.com/a/56327069/715269

6 Answers 6

The proper way that actually works:

URL resource = YourClass.class.getResource("abc"); Paths.get(resource.toURI()).toFile(); 

It doesn’t matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.

(The seemingly obvious new File(resource.getPath()) doesn’t work for all paths! The path is still URL-encoded!)

Or presumably you could just do: new File(resource.toURI()).getAbsolutePath(); (i.e. I don’t think you need the Path object?)

Thanks! This almost worked for me. But I had to make one change: YourClass.class.getClassLoader().getResource(«abc»);

You could alternativly do new File(YourClass.class.getResource(«abc»).toURI().getPath()) if you wanted to.

I don’t understand how this have worked for so many people without the starting slash: .getResource(«/abc»)

You can use ClassLoader.getResource method to get the correct resource.

URL res = getClass().getClassLoader().getResource("abc.txt"); File file = Paths.get(res.toURI()).toFile(); String absolutePath = file.getAbsolutePath(); 

Although this may not work all the time, a simpler solution —

You can create a File object and use getAbsolutePath method:

File file = new File("resources/abc.txt"); String absolutePath = file.getAbsolutePath(); 

An advice of limited use, as it relies on the working directory to be the maven root. And even then, you should rather use target/classes/abc.txt to reference the file, as this is the canonical place where Maven puts resource files after processing (for example, the maven-resources plugin might have done property substitution on abc.txt). It’s much better to use the abc.txt via getResource() from the classpath.

What if an end-user is running your application as an executable JAR? Then there won’t be a physical File at all. This is another reason why you should use getResource(), and e.g. open input stream to it depending on what you want to do with it.

Can this be removed as the correct answer? @Karol S answered below — that should be the correct answer (hence the upvote discrepancy)

Technically it works, I guess. Got the root path correct but it did not point to where my actual resource folder is for the module.

You need to specifie path started from /

URL resource = YourClass.class.getResource("/abc"); Paths.get(resource.toURI()).toFile(); 

In my case it is a .png file, and when I add the above, I get resources as null. Please can you tell what to do for a .png or .pdf file present in the resources folder?

Create the classLoader instance of the class you need, then you can access the files or resources easily. now you access path using getPath() method of that class.

 ClassLoader classLoader = getClass().getClassLoader(); String path = classLoader.getResource("chromedriver.exe").getPath(); System.out.println(path); 

There are two problems on our way to the absolute path:

  1. The placement found will be not where the source files lie, but where the class is saved. And the resource folder almost surely will lie somewhere in the source folder of the project.
  2. The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.

The following code will give us all useful paths:

 URL localPackage = this.getClass().getResource(""); URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation(); String localDir = localPackage.getPath(); String loaderDir = urlLoader.getPath(); System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir); 

Here both functions that can be used for localization of the resource folder are researched. As for class , it can be got in either way, statically or dynamically.

If the project is not in the plugin, the code if run in JUnit, will print:

loaderDir = /C. /ws/source.dir/target/test-classes/ localDir = /C. /ws/source.dir/target/test-classes/package/ 

So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can’t use getResource(resourceFolderName) , for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.

If the class is in the package that is in the plugin, the output of the same test will be:

loaderDir = /C. /ws/plugin/bin/ localDir = /C. /ws/plugin/bin/package/ 

So, again we should go up and down the folder tree.

The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:

loaderDir = /C. /ws/plugin/ localDir = /package/ 

Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.

You can insert the code into yours and see the paths that you have.

Источник

Оцените статью