How to load properties from resources folder? - java

I've been able to get the following to work by loading a properties file which exists in the same folder as the class files (the bin folder)
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("config.properties");
I want to load the config.properties file from a resources folder which is at the same level as the bin folder. If I pass it "resources/config.properties" it finds the file in /bin/resources, but passing it "/resources/config.properties does not look above the bin folder like I want.
Ideas?

Try to use Properties like this:
Properties props = new Properties();
InputStream resourceStream = Your_Class_Name.class.getResourceAsStream("config.properties"))
props.load(resourceStream);

class.getResourceAsStream method loads from jars and folders defined in your classpath. If you have that config.properties file under resources folder, you should add that folder in your classpath.
Something like
java -classpath "resources" ...

Related

Trouble reading/writing file from relative path

I've been trying to read and write to a file under my resources directory in my project. However, regardless of what I seem to do it doesn't allow me to do so.
This is my project hierarchy for reference:
Out of all these:
Paths.get("memes.txt")
Paths.get("resources/memes.txt")
Paths.get("/resources/memes.txt")
...
None have worked. What am I doing wrong?
Is it a Maven project ?
Try this :
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
Ref : https://www.mkyong.com/java/java-read-a-file-from-resources-folder/
Your application can be packed as .jar file - a zip format.
There, or in the built classes directory should be memes.txt. A so-called resource, and in case of a jar not really a file system file. But is located on the class path.
URL url = getClass().getResource("/memes.txt");
InputStream in = getClass().getResourceAsStream("/memes.txt");
The path is relative to the package directory of the class, or absolute as above.
Try it using "../resources/memes.txt" with ".." you go up one directory from your current file (i assume that you are using the code in SwearTest.java)

Relative path Not works

I have a folder structure like:
myDir
resources
myConfig.cfg
in
infile.txt
myProgram.jar -->runnable jar file
I tried to use the relative path ./in/infile.txt
I'm mentioning these relative paths from myConfig.cfg.
In code, i use like,
Properties properties = new Properties();
properties.load(new FileInputStream("./resources/myConfig.cfg"));
What is the error ?
The same worked for another jar and the same path.
Try this
properties.load(this.getClass().getResourceAsStream("/myConfig.cfg"));
Actually when compiled resource folder is not used but all the resource files are moved under "classes" dir

Java load properties file correctly

I have the following project structure:
ProjectName/src/java/com/main/Main.java
And I have a properties file in the following folder:
ProjectName/config/settings.properties
Now I tried to load the properties file in the Main.java with:
InputStream input = Main.class.getResourceAsStream("/config/settings.properties");
Properties prop = System.getProperties();
prop.load(input);
But this does not work. How is it the right way to do it?
Edit: I got the following error:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
Edit2: Now it works with eclipse. I did the following (adapted from getResourceAsStream() is returning null. Properties file is not loading)
1) This directory [config] must be put into the "build path". Right-click the directory in the Package Explorer or Project Explorer view, select "Build Path", then "Use as Source Folder". Note: This build path will be the class path for the project, when you run it.
2) As the config directory now is part of your class path and contains your properties file, you can simply load it with InputStream input = Server.class.getClassLoader().getResourceAsStream("settings.properties");
This works well for eclipse but not yet for a jar. I think I also have to add the build path somehow to the ant script.
How can I do that?
Edit3: If I take the settings.properties out of the config folder in the jar, then it works. Why? I want it in the config folder in the jar too.
Use following :
InputStream input = Main.class.getResourceAsStream("../../../../config/settings.properties");
Properties prop = System.getProperties();
prop.load(input);
By adding ../ I am getting 1 step backward in your filesystem. In your code you were using /config....., which means C:/config..... (if it is in C drive).
The following will also work in your case. (but not in zipped file)
InputStream input = new FileInputStream("config/settings.properties");
Properties prop = System.getProperties();
prop.load(input);
getResourceAsStream find files relatively compiled (class) files on in jar file. Example:
Your compiled files are in bin directory than you should put properties file to bin/config/settings.properties for give access to it.
You are using maven. So follow the maven structure and keep your resources like prop, xml etc files in resource folder and then call.
So folder structure would be like this
src/main/resource|
|
config|
|
settings.properties
InputStream input = Main.class.getClass().getResourceAsStream("/config/settings.properties");
Three things
You need add the settings.properties to a jar (can be the same jar as your Main)
Your classpath should include this jar
You need to use the context Class Loader to load the properties file in you Main.
Classloader cl = Thread.currentThread().getContextClassLoader();
cl.getResourceAsStream("settings.properties");

Load a properties file in a jar file

I was trying to work on a java program with requires a properties file attached to the jar. Thus, i did jar the program, and unjar it to attach a properties file. I have a class, MyClass, which requires the properties file. Thus, i basically put the properties file to the same folder as MyClass.class. Then I jarred it back.
In my MyClass.java, i was trying to access the properties by:
Properties prop = new Properties();
prop.load(MyClass.class.getClassLoader().getResourceAsStream("prop.properties"));
Where prop.properties is in the same folder as my MyClass.class.
It failed to load it. Any help will be appreciated !
Thanks,
ClassLoader.getResourceAsStream() treats the path as relative to the root of the classpath, i.e. it looks for resources at the root level of each JAR or directory on the class loader.
You probably want Class.getResourceAsStream, which treats the path as being relative to the package of the class in question. You also need to make sure to close the stream once you've read it.
Properties prop = new Properties();
InputStream in = MyClass.class.getResourceAsStream("prop.properties");
try {
prop.load(in);
} finally {
in.close();
}
If MyClass is in the package com.example then this will load com/example/prop.properties from the JAR.

How to get a path to a resource/file out of a Java JAR file

I'm trying to get the path to a file that it is located out of the java jar and I don't want to use an absolute path. An exampel: lets say that the jar is located in ~/lib/myjar.jar and the file is located in the same folder. What I've trying is something like this, but it fails:
File myfile = new File(this.getClass().getResource("../../../").toURI());
Note: my package is com.contro.gui, that's why I have "../../../", in order to acces to the "root"
I'm not sure how I can access to the file. Any suggestion?? And what about if the file that I want to access is in other folder like ~/res/ ???
If the file is in the same directory as the jar, I think this will work (feels fairly hacky, but...):
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = new File(url.toURI());
File dir = myfile.getParentFile(); // strip off .jar file
(Haven't tested this, but it seems feasible. Will only work with file-based jars of course).
If the file is in some random location, I think you will need to either pass in parameters or check "known" locations like user.home. (Or, you could always put the file in the jar a use getResource().)
No just do
File FileName = new File(".");
String Directory = FileName.getCanonicalPath();
that will get you the parent directory of your class in a file or jar just remember to set the directory if it's in a jar like this "NameOfJar\NameOfFolder\etc"

Categories

Resources