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();
}
}
}
This question already has answers here:
Reading a resource file from within jar
(15 answers)
Closed 6 years ago.
I am using maven web application.
The following is my project structure where I have placed my properties file.
The following is my code which I am using to read this file:
public static Properties loadProducerProperty() throws FileException {
Properties myProperties = new Properties();
try {
String resourceName = "newproperties.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
myProperties.load(resourceStream);
}
} catch (FileNotFoundException e) {
throw new FileException();
} catch (IOException e) {
throw new FileException();
}
return myProperties;
}
But I am getting FileNotFound Exception
I have gone through the following link and tried other things also but I am getting the same error :
Cannot load properties file from resources directory
What I am doing wrong here.
Thank you
Add a slash in front of the filename:
String resourceName = "/newproperties.properties"; // could also be a constant
This question already has answers here:
How to read properties file in web application? [duplicate]
(3 answers)
Closed 7 years ago.
My PC's operating system is Windows 7 64-bit.
I created a very simple Dynamic Web Project app in Eclipse:
I have a app.properties file in WEB-INF/classes directory with these properties:
DefaultMaximumBatchSize=1000
DAOFactory=MSSQLSERVER
I have a class AppProperties which reads the above file into a Properties object at startup using getResourceAsStream:
public class AppProperties {
private static final Properties APP_PROPERTIES;
static {
InputStream inputStream = null;
APP_PROPERTIES = new Properties();
try {
inputStream = AppProperties.class.getResourceAsStream("/WEB-INF/classes/app.properties");
System.out.println("AppProperties: inputStream=" + inputStream);
if (inputStream != null) {
APP_PROPERTIES.load(inputStream);
}
} catch (Exception e) {
System.out.println("AppProperties: Exception occured; e=" + e);
}
}
public static String getValue(String propertyName) {
if (propertyName == null || propertyName.equalsIgnoreCase(""))
return null;
else
return APP_PROPERTIES.getProperty(propertyName);
}
}
I have a listener class AppContextListener:
public class AppContextListener implements ServletContextListener {
public AppContextListener() {
}
public void contextInitialized(ServletContextEvent arg0) {
String defaultMaxBatchSize = AppProperties.getValue("DefaultMaximumBatchSize");
System.out.println("AppContextListener: contextInitialized(ServletContextEvent): defaultMaxBatchSize=" + defaultMaxBatchSize);
}
public void contextDestroyed(ServletContextEvent arg0) {
}
}
I deployed the app to JBoss 4.2.3, run the JBoss 4.2.3 and I get this output in server.log:
AppProperties: inputStream=java.io.FileInputStream#1adde645
AppContextListener: contextInitialized(ServletContextEvent): defaultMaxBatchSize=1000
Perfect.
I then deployed the same app to WildFly 8.2.1, run the WildFly 8.2.1 and I get this output in server.log:
AppProperties: inputStream=null
AppContextListener: contextInitialized(ServletContextEvent): defaultMaxBatchSize=null
What happened? What is the correct way to read properties file in WildFly from WEB-INF/classes directory?
Class.getResourceAsStream() looks for a resource in all of the directories and jars that constitute the classpath of the application.
So, if you start a java program with
java -cp foo;bar.jar com.baz.Main
And you use SomeClass.class.getResourceAsStream("/blabla/app.properties"), The classloader will look for the app.properties file under foo/blabla, and in the blabla directory of bar.jar.
Now, in a webapp, what constitutes the classpath of the webapp is
the directory WEB-INF/classes
all the jar files under WEB-INF/lib
So, if you call
AppProperties.class.getResourceAsStream("/WEB-INF/classes/app.properties")
the classloader will look for app.properties in
/WEB-INF/classes/WEB-INF/classes
<all the jar files of WEB-INF/lib>/WEB-INF/classes
The conclusion is that, to load an app.properties file located in WEB-INF/classes, what you need is
AppProperties.class.getResourceAsStream("app.properties")
JBoss shouldn't have worked.
Class.getResourceAsStream retrieves the resource from the classpath and the webapp root folder is not in the classpath.
The WEB-INF/classes folder is. Use getResourceAsStream("/app.properties"), and remember to close the stream:
private static final Properties APP_PROPERTIES = new Properties();
static {
try (InputStream inputStream = AppProperties.class.getResourceAsStream("/app.properties")) {
System.out.println("AppProperties: inputStream=" + inputStream);
if (inputStream != null)
APP_PROPERTIES.load(inputStream);
} catch (Exception e) {
System.out.println("AppProperties: Exception occured; e=" + e);
}
}
Now, if app.properties is always next to AppProperties.class, instead of at the root, make the name unqualified (remove the /). This will work even when your class is in a package (and it is in a package, right?).
Try
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream("/my.properties");`
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.
This question already has answers here:
Where to place and how to read configuration resource files in servlet based application?
(6 answers)
Closed 7 years ago.
I am using servlets where I hard-code the database connection details, so if make any change I have to recompile the code. So instead I'd like to use a .properties file (which I can modify later) and use that as the source for my database connection.
The problem is I don't know how to read the property file. Could someone please help me to read the file?
. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create application properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .
Example is coming from here Properties (Java)
The methods of Properties can throw exceptions.
- When the file path is not valid (FileNotFoundException). Please try to create a File object and check, whether the File is existing.
- ...
You may take a look at Apache Commons Configuration. Using it you can read properties file like that:
Configuration config = new PropertiesConfiguration("user.properties");
String connectionUrl = config.getString("connection.url");
This information regarding file location may be also important:
If you do not specify an absolute
path, the file will be searched
automatically in the following
locations:
in the current directory
in the user home directory
in the classpath
So in case of reading properties file in a servlet you should put properties file in a classpath (e.g. in WEB-INF/classes).
You can find more examples at their website.
You can use java.util.Properties
The biggest problem in reading a property file in web application is that you actually don't know about the actaul path of the file. So we have to use the relative path and for that we have to use various functions and classes like getresourceAsStream(), InputStream, FileinputStream etc.
And the method getReourceAsStream behaves differently in static and non static methogs..
you can do this in below way
Non Static
InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties");
Static
InputStream input = ReadPropertyFile.class.getClassLoader().getResourceAsStream("config.properties");
For complete reference you can follow these links..
http://www.codingeek.com/java/using-getresourceasstream-in-static-method-reading-property-files
http://www.codingeek.com/java/read-and-write-properties-file-in-java-examples/
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
Properties p = new Properties();
p.load(in);
in.close();
The below code, will add a Listener which checks for file configured with dbprops system property. For every given interval it will look if the file is modified, if it is modified it will load the Properties from the file.
package com.servlets;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class DBPropsWatcherListener
implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
Timer timer = new Timer("ResourceListener");
timer.schedule(new MyWatcherTask(servletContext), 15);
}
public void contextDestroyed(ServletContextEvent event)
{
}
private class MyWatcherTask extends TimerTask
{
private final ServletContext servletContext;
private long lastModifiedTime = -1;
public MyWatcherTask(ServletContext servletContext)
{
this.servletContext = servletContext;
}
public void run()
{
try {
File resourceFile = new File(System.getProperty("dbProps"));
long current = resourceFile.lastModified();
if (current > lastModifiedTime) {
java.io.InputStream dbPropsStream = new FileInputStream(resourceFile );
java.util.Properties dbProps = new java.util.Properites();
dbProps.load(dbPropsStream);
realoadDBProps();
}
lastModifiedTime = current;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
Below program read the properties file a display using key value pair
File f1 = new File("abcd.properties");
FileReader fin = new FileReader(f1);
Properties pr = new Properties();
pr.load(fin);
Set<String> keys = pr.stringPropertyNames();
Iterator<String> it = keys.iterator();
String key, value;
while (it.hasNext())
{
key = it.next();
value = pr.getProperty(key);
System.out.println(key+":"+value);
}
}
If your application is small enough with only a handful of properties coming from just one or two property files, then I would suggest to use the JDK's own Properties class which load the properties from a file and use it just like the way you use a hashtable. Properties class itself inherits from Hashtable. But, your application is significantly large with sizable number of properties coming from different sources like property files, xml files, system properties then I would suggest to use Apache commons configuration. It presents a unified view of properties from across different configuration sources and allows you to define an override and preference mechanism for common properties appearing in different sources. Refer this article http://wilddiary.com/reading-property-file-java-using-apache-commons-configuration/ for a quick tutorial on using the commons configuration.
This may work::
Properties prop = new Properties();
FileReader fr = new FileReader(filename);
prop.load(fr);
Set<String> keys = pr.stringPropertyNames();
//now u can get the values from keys.
The Properties class has a convenient load method. That's the easiest way to read a java properties file.
That is a good idea to read the database values from properties file
You can use a properties class from Util package. The important thing to keep in mind is closing the stream after reading the file or writing the file to disk. Otherwise it causes problems. Here is an example for your reference:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class App
{
public static void main( String[] args )
{
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output
localhost
mkyong
password
ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");
assuming mybundle.properties file is in classpath
Read this.Usually the properties file is kept in the classpath so that this method can read it.