Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file in the resources folder in Java

I want to read the file in my resource folder in my Java project. I used the following code for that

MyClass.class.getResource("/myFile.xsd").getPath();

And I wanted to check the path of the file. But it gives the following path

file:/home/malintha/.m2/repository/org/wso2/carbon/automation/org.wso2.carbon.automation.engine/4.2.0-SNAPSHOT/org.wso2.carbon.automation.engine-4.2.0-SNAPSHOT.jar!/myFile.xsd

I get the file path in the maven repository dependency and it is not getting the file. How can I do this?

like image 365
Malintha Avatar asked Oct 01 '13 12:10

Malintha


People also ask

How do I get resources in Java?

The getResource() method of java. lang. Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of URL object.

What are resource files in Java?

In the Java programming language a resource is a piece of data that can be accessed by the code of an application. An application can access its resources through uniform resource locators, like web resources, but the resources are usually contained within the JAR file(s) of the application.

What is Java resources folder?

The resources folder belongs to the maven project structure where we place the configuration and data files related to the application. The location of the folder is “ src/main/resources “. When packaging the application as jar file, the file present in the resources folder are copied in the root target/classes folder.


2 Answers

You need to give the path of your res folder.

MyClass.class.getResource("/res/path/to/the/file/myFile.xsd").getPath();
like image 86
Rahul Avatar answered Oct 08 '22 01:10

Rahul


Is your resource directory in the classpath?

You are not including resource directory in your path:

MyClass.class.getResource("/${YOUR_RES_DIR_HERE}/myFile.xsd").getPath();
like image 31
Matt Avatar answered Oct 08 '22 01:10

Matt