Reading Properties file inside conf folder - java

I have a properties file which is located under conf folder. conf folder is under the project root directory. I am using the following code.
public class PropertiesTest {
public static void main(String[] args) {
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("/conf/sampleprop.conf");
Properties prop = new Properties();
try {
prop.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(prop.getProperty("TEST"));
}
}
But I get nullpointer exception.
I have tried using
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("./conf/sampleprop.conf");
and
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("conf/sampleprop.conf");
But all result in nullpointer exception.
Can anyone please help.
Thanks in advance

Try to recover your working directory first:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working dir: " + workingDir);
and then is simple:
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(workingDir+ "/yourFilePath"));
String first= propertiesFile.getProperty("myprop.first");
Regards, fabio

The getResourceAsStream() method tries to locate and load the resource using the ClassLoader of the class it is called on. Ideally it can locate the files only the class folders .. Rather you could use FileInputStream with relative path.
EDIT
if the conf folder is under src, then you still be able to access with getResourceAsStream()
InputStream inputStream = Test.class
.getResourceAsStream("../conf/sampleprop.conf");
the path would be relative to the class from you invoke getRes.. method.
If not
try {
FileInputStream fis = new FileInputStream("conf/sampleprop.conf");
Properties prop = new Properties();
prop.load(fis);
System.out.println(prop.getProperty("TEST"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NOTE: this will only work if it is Stand alone application/in eclipse. This will not work if its web based (as the root will be Tomcat/bin, for eg)
I would suggest to copy the configuration file at designated place, then you can acess at ease. At certain extent 'System.getProperty("user.dir")' can be used if you are always copying the file 'tomcat` root or application root. But if the files to be used by external party, ideal to copy in a configurable folder (C:\appconf)

Your code works like a charm! But you might have to add the project root dir to your classpath.
If you work with Maven, place your configuration in src/main/resources/conf/sampleprop.conf
When invoking java directly add the project root dir with the java -classpath parameter. Something like:
java -classpath /my/classes/dir:/my/project/root/dir my.Main

Related

Properties file not loading and updating for relative path but working fine for absolute path

I am trying to access a properties file from the src/main/resources folder but when I try to load the file using a relative path it is not getting updated. But it is working fine for an absolute path.
I need the dynamic web project to work across all platforms.
public static void loadUsers() {
try(
FileInputStream in = new FileInputStream("C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties")) {
// write code to load all the users from the property file
// FileInputStream in = new FileInputStream("classpath:users.properties");
users.load(in);
System.out.println(users);
in.close();
}
catch(Exception e){
e.printStackTrace();
}
First of all you are using Spring, at least that is what the tags at the bottom say. Secondly C:\\Users\\SohamGuha\\Documents\\work-coding\\work-coding\\src\\main\\resources\\users.properties is the root of your classpath. Instead of loading a File use the Spring resource abstraction.
As this is part of the classpath you can simply use the ClassPathResource to obtain a proper InputStream. This will work regardless of which environment you are in.
try( InputStream in = new ClassPathResource("users.properties").getInputStream()) {
//write code to load all the users from the property file
//FileInputStream in = new FileInputStream("classpath:users.properties");
users.load(in);
System.out.println(users);
} catch(Exception e){
e.printStackTrace();
}
NOTE: you are already using a try with resources so you don't need to close the InputStream that is already handled for you.
Changing things inside your application simply won't work, as this would mean you could change resources (read classes) in your jar which would be quite a security risk! If you want something to be changable you will have to make it a file outside of the classpath and directly on the file-system.
Try the following code
import java.io.FileInputStream;
import java.io.IOException;
public class LoadUsers {
public static void main(String[] args) throws IOException {
try(FileInputStream fis=new FileInputStream("src/main/resources/users.properties")){
Properties users=new Properties();
users.load(fis);
System.out.println(users);
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

Open a properties file from a class in a Dynamic Web Project

I'm using Eclipse for EE Developer.
I need to access to a properties file (db.properties) from a class's method (DBQuery.java).
The class is located inside a package inside the src folder.
For the properties file i tried almost everything that i could find over the net to make it work, but looks like i can't.
The properties file is located inside the WebContent folder, and i'll add the code with which i'm trying to load this file:
public class DBQuery {
public static String create_DB_string(){
//the db connection string
String connString = "";
try{
Properties props = new Properties();
FileInputStream fis = new FileInputStream("db.properties");
props.load(fis);
fis.close();
/* creating connString using props.getProperty("String"); */
}
catch (Exception e) {
System.out.println(e.getClass());
}
return connString;
}
}
So my question is, where to put the properties file, and which is the correct way to load it?
You can put this propertie file within your java package for example com/test and use following:
getClass().getResourceAsStream( "com/test/myfile.propertie");
Hope it helps.

Can't find resource outside the jar

I am trying to read properties which is located external to the jar file of my code.using ResourceBundle but its unable to read the property file locations.properties. The property file is located under resource folder and both jar and resource folder are under same directory.
myDir
--> myJar.jar
--> resource
-->locations.properties
I don't know whats wrong with my code below:
public static ResourceBundle getResourceBundle(String fileName) throws MalformedURLException{
if (resourceBundle == null) {
File file = new File("resource/"+fileName);
URL[] urls = { file.toURI().toURL() };
ClassLoader loader = new URLClassLoader(urls);
resourceBundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);
}
return resourceBundle;
}
And this is how am invoking ResourceBundle object:
ResourceBundle locationBundle = null;
try {
locationBundle = ReadPropertyUtil.getResourceBundle(propFileName);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please guide whats wrong with this code and whats the correct way of reading an external properties file.
Get Jar file path.
Get Parent folder of that file.
Use that path in InputStreamPath with your properties file name.
Properties prop = new Properties();
try {
File jarPath=new File(YourClassNameInJar.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String propertiesPath=jarPath.getParentFile().getAbsolutePath();
System.out.println(" propertiesPath-"+propertiesPath);
prop.load(new FileInputStream(propertiesPath+"/resource/locations.properties"));
} catch (IOException e1) {
e1.printStackTrace();
}
Well, I figured out the error myself. I was appending the fileName to the directory location File file = new File("resource/"+fileName); which was wrong.
All I had to do was to first get the present working directory name using
System.getProperties("user.dir") //this gives me the path of my current directory
and passing only the directory name to file object.
File file = new File("resource/");
And then load the bundle using the specified file name.
resourceBundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);
ResourceBundle automatically looks into the directory and loads the file specified by the fileName

Cannot load properties from jar

I have small app and I tested and packed to jar and am trying to run it but I have error.
Here is my project structure:
src
-kie.template
----- ServerMain.java ==> Class with main
-kie.template.util
---- PropUtils.java
---- server.properties
target
-kietemplate.jar
---- lib
In the main method, PropUtils class reads properties.
public class PropUtils {
private static final String PROPERTIES = "server.properties";
public static Properties load() {
Properties properties = new Properties();
InputStream is = null;
try {
properties.load(PropUtils.class.getResourceAsStream(PROPERTIES));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is!=null) try{is.close();}catch(IOException e){}
}
return properties;
}
}
}
When I run the ServerMain class directly, it works fine. But after I packed it to jar and run, it shows error:
java -cp lib -jar kietemplate.jar
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at au.org.jeenee.kie.template.util.PropUtils.load(PropUtils.java:26)
The properties file is in the directory when I look into the jar file.
jar tf kietemplate.jar
Any help would be appreciated very much.
EDIT:
I changed the logic to read properties:
Properties properties = new Properties();
InputStream is = null;
try {
File file = new File("server.properties");
is = new FileInputStream(file);
properties.load(new InputStreamReader(is));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is!=null) try{is.close();}catch(IOException e){}
}
It requires the properties file in parent directory of the jar file.
Your code works fine on my computer, both from the JAR and the filesystem.
A possible cause for that behaviour is the filesystem being case insensitive, but the jar file being case sensitive. But we really can't tell from the source code alone.

I'm having trouble reading a properties file using FileInputStream

I'm working on a web application, and I have created a properties file in package com.xx.yy. I need to read this file from a class in author package com.aa.bb.
I have the folowing code:
try {
FileInputStream fileInputStream = new FileInputStream("com/xx/yy/myfile.properties");
internationalizationFile = new Properties();
internationalizationFile.load(fileInputStream);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
but it doesn't work!!
Have you tried to load the resource through the class loader? like:
InputStream in = this.getClass().getClassLoader.getResourceAsStream("com/xx/yy/myfile.properties");
1) I would print out the absolute path to make sure the file / resource is in the correct location.
getResourceAsStream() vs FileInputStream
2) I would use getResourceAsStream, same reference.

Categories