I'm developing a Dynamic Web Project in Eclipse. I created a .properties file for store database details (Username, Password etc.). I added it by right clicking on the project and New -> File . I used the Java util package Properties class. But it does not working. I can not retrieve any property from the file. Here is the code I used,
Properties prop = new Properties();
try {
prop.load(new FileInputStream("database.properties"));
String db = prop.getProperty("database");
String userName = prop.getProperty("dbuser");
String password = prop.getProperty("dbpassword");
} catch (IOException ex) {
ex.printStackTrace();
}
Is there something wrong or Is there any particular place where I should put properties file.
What you did is correct, ie right clicking the project and new--file.You have to Put your properties where you start your jvm from. Please look into the attached image. The properties file is marked in red. Look if your properties file is also located something like this.
Also add this in your code to find out where to put your file:
System.out.println(new File(".").getAbsolutePath());
For more details please follow this link- FileNotFoundException when using java properties file
Normally, you make sure the properties file is in the project runtime classpath (e.g. WEB-INF/classes) and then load it using either the System classloader or the property file handler's classloader, i.e. (Freehand typing from memory -- NOT COMPILED)
try{
Properties p = new Properties();
InputStream in = MyPropertyHandler.getClass()
.getClassLoader()
.getResourceAsStream("com/package/props/database.properties");
p.load(in);
catch(IOException e){
e.printStackTrace(System.err);
}
I'm betting you aren't pointing at the correct location. Make sure you're properties file is in the correct place. Using that code, I believe it is looking for ${CURRENT_WORKING_DIR}/database.properties, which is the case of a web app in eclipse is WEB-INF/classes (i think).
You should instead be using the more portable java.util.Properties#load(InputStream) with the result of javax.servlet.ServletContext#getResourceAsStream(String).
Try to give absolute path or relative path to the proprty file, also check this propery file path has been add to source folders or not, if not it will not be copied to your classes folder. (Right cclick on project , check java build path under source tab.
You should have .properties file in same package as class that is using it.
Or better, read properties file with getResourceAsStream method (otherwise you can have some problem later when you'll have file in .war archive).
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("database.properties");
Related
My Property file location is WebRoot/WEB-INF/Test/property files/Question.properties
Now I want to load the property file using FileInputStream. So I wrote the below code.
Properties pr = new Properties();
pr.load(new FileInputStream("WebRoot/WEB-INF/Test/property files/Question.properties"));
By the above code I got java.io.FileNotFoundException.I am using myeclipse for my development. Can any one suggest the path to read my properties.
You are opening it relative to the current directory. Do you know what the current directory is? Try creating a:
File f = new File("WebRoot/WEB-INF/Test/property files/Question.properties");
Then printing or debug the absolute path of the File object. This will tell you what file you are actually trying to open (i.e. full path).
However, if you are trying to open a 'resource' bundled with your web app (as suggested by /WEB-INF/ being in the path) this is probably not a good way to do it. One alternative is to build your 'resource' into one of your application's .jar files.
See here, for a related answer:
Refer to a web page inside a jar file
use the method InputStream java.lang.Class.getResourceAsStream(String name) instead, this will work when you run your class within eclipse and outside eclipse. and use the same path as what you have mentioned in your code and append "/" at the front.
Hope this helps !
Do one thing right click on Question.properties file click on the properties get the Location of the file.
Properties pr = new Properties();
pr.load(new FileInputStream("Location of the file"));
I have created a Java program to compare scripts saved as files in the version management tool to those loaded in our database. It's a simple program, runs through start to finish and outputs to the console when it finds a discrepancy. Now I want to load the database URL, username and password as well as the location of my files from a .properties file.
I did assume that if I put the file on the classpath it would be visible from my Java program:
Properties values = new Properties();
try
{
File checkPackages = new File("myfile.properties");
if(!checkPackages.exists()) throw new FileNotFoundException();
values.load(new FileReader(checkPackages));
}
catch(FileNotFoundException fnfe) {}
I also wanted to save this whole program to a .jar file so that it would be that bit more usable. Unfortunately, the only way I have found to reference the .properties file is to have it in the directory where I am running java.exe. The PATH or the CLASSPATH don't seem to apply??
I found an Oracle site about the .jar file's Manifest file as I was hoping there'd be an answer there, but the Class-path: element in the manifest only seems to refer to .jar files that are not in the .jar (and not .properties files that are!)
Questions:
Is there any way to wrap the .properties file into the .jar file so that my user doesn't have to know it is there?
Is there any way to wrap the Oracle driver .jar into the app's .jar so my user doesn't have to know it is there (Oracle says this needs 'custom code')?
TIA
You can get the resources in your classpath (even when sealed in the JAR) by using the ClassLoader#getResource() and ClassLoader#getResourceAsStream() methods.
For example:
Properties values = new Properties();
values.load(ThisClass.class.getClassLoader().getResourceAsStream("myproject.properties"));
// umm, don't forget to close the stream, this code is just an example usage
Note that storing the username and password to any database in a program is considered a heavy security risk.
One of the appraoch can be to use the -D switch to define a system property on a java command line. That system property may contain a path to your properties file.
E.g
java -cp ... -Dmyproject.properties=/path/to/my.app.properties
my.package.App
Fetch the property in your code as mentioned here:
String propPath = System.getProperty( "myproject.properties" );
final Properties myProps;
final FileInputStream in = new FileInputStream( propPath );
try
{
myProps = Properties.load( in );
}
finally
{
in.close( );
}
Well, I would recommend to encrypt the sensitive data (username, password, url in this case) with public and private keys rather than hiding it. It is afterall not hard to deflate any jar file (which is essentially a zip format) and trace the .properties file
I am developing a Java Application (not a web app, no server etc) using Netbeans 7.0.1 IDE.
Right now I have an issue with reading any properties /or any other file from my java class.
Here is what I am doing
FileReader f = new FileReader( new File(args[0]) );
BufferedReader r = new BufferedReader(f);
in the argument I pass the file name like connector.properties (I have the file in the same package as this class). the project when run gives the error below
Can't load: connector.properties : Exception is: connector.properties (The system cannot find the path specified)
why am I not able to read the properties file? whats the root of my classpath?
when I set the 'Working Folder' (right clicking the project and selecting 'Run' section) to the package level like C/complete/path/to/the/package
only then the properties file is read.
I want to know why do I need to set the working folder in Netbeans project and how can I read the file without setting the working folder?
This is because you are not using a class path reader to read your properties file. Your above code reads a hard path.
And, to read a properties file from a class path, you can use apache commons Configuration's file properties reader. There are several options there for reading properties file and the stream these input files are coming from e.g. Classpath.
You can use this.getClass().getResourceAsStream() to get a stream and then use .load:
http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.InputStream)
to load the properties. This extends readily to reading any file in the classpath.
You should put your properties file in project folder because it's default working folder, not put in the package of class to be run.
Properties properties = new Properties();
String propertiesFileName = "config.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFileName);
properties.load(inputStream);
This code will do the trick when reading your properties file.
I was using Unix before to compile and edit my Java. In that I have used property files right inside my current working directory where the class file exists. Now i have switched to Eclipse IDE. I dont know how to add the same properties file here in Eclipse. Please help me.
Create Folder “resources” under Java Resources folder if your project doesn’t have it.
create config.properties file with below value.
/Java Resources/resources/config.properties
for loading properties.
Properties prop = new Properties();
InputStream input = null;
try {
input = getClass().getClassLoader().getResourceAsStream("config.properties");
// load a properties file
prop.load(input);
// 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();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the package explorer, right-click on the package and select New -> File, then enter the filename including the ".properties" suffix.
It should work ok as it is in Unix, if you have properties file in current working directory. Another option would be adding your properties file to the classpath and getting the inputstream using this.getClass().getClassLoader().getResourceAsStream("xxxxx.properties");
More here
steps:
Right click on any package where you want to create your .properties file
or create a new package as required
now select new then select file (if you dont find file then go to location of your package and create it there)
now named it as yourfilename.properties
If you have created a Java Project in eclipse by using the 'from existing source' option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select 'Create project from existing source' and then select your existing project folder. The wizard will take care of the rest.
Right click on the folder within your project in eclipse where you want to create property file
New->Other->in the search filter type file and in the consecutive window give the name of the file with .properties extension
To create a property class please select your package where you wants to create your property file.
Right click on the package and select other.
Now select File and type your file name with (.properties) suffix.
For example: db.properties.
Than click finish.
Now you can write your code inside this property file.
If you are working with core java, create your file(.properties) by right clicking your project. If the file is present inside your package or src folder it will throw an file not found error
I am working on deploying a J2ee application that I have previously been deploying in JBOSS into Weblogic 10.3.1.0. I am running into an issue with external properties files. In Jboss I can just put the properties files into $JBOSS_HOME/server/default/conf, and they are loaded onto the system classpath and I can access them without any problems. I was able to put shared libraries into $MIDDLEWAREHOME/user_projects/domains/mydomain/lib and they were loaded into the system classpath without any problems but I am unable to load properties files.
Does anyone know how to include external properties files in Weblogic?
Thanks,
I figured this out and have it working the way I would expect. First I did try the suggestions as above. If i added a folder to my classpath, or put the properties files in a folder on my classpath, the jars in the file were picked up, but not properties files. If i put my properties files in a jar, and put them in a folder on my classpath everything worked. But I did not want to have jar my files everytime a change was made. The following works in my env.
If i place the properties files in %WEBLOGIC_HOME%/user_projects/domains/MYDOMAIN then they are getting picked up, without having to be placed in a jar file.
In weblogic jars will be loaded from the lib and the non jar files will be loaded from the domain folder
There are ways to read properties file in Java from weblogic classpath
One (Properties file located in the weblogic domain): Drop the properties file inside the Domain directory. This way the properties file is added to the weblogic classpath automatically and we can read from Java using resourceAsStream.
Two (Properties file from a User defined location):The advantage with this approach is that the property file can reside outside the JAR or EAR file and can be modified conveniently.
package com.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertyFileExample {
private static Properties prop;
public static void myMethod() {
InputStream is = null;
try {
prop = new Properties();
String propFilePath = System.getProperty(“propFileLocation“);
InputStream iStream = PropertyFileExample.class.getClassLoader().getResourceAsStream(propFilePath);
//Note that the propFilePath is a -Dparam defined below in the setDomainEnv
prop.load(iStream);
prop.getProperty(“dbuser”);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the weblogic setDomainEnv (under bin) => we need to pass the location of the property file as a -D argument to JAVA_OPTIONS
set JAVA_OPTIONS=%JAVA_OPTIONS% -DpropFileLocation =/dev/file/properties/some.properties
You can set a directory on the classpath and Place your custom properties file in that folder/directory. So that, the entire directory along with property file will be on classpath.
To set the directory on the classpath in weblogic 10.3.x
Create a folder in %DOMAIN_HOME%\config\ folder. example appConfig.
Place your custom property file (Let's say config.properties) in appConfig directory/folder.
Modify the setDomainEnv.cmd (Windows) to include appConfig in the classpath by setting %DOMAIN_HOME%\config\appConfig as value to EXT_POST_CLASSPATH(this variable is already defined in the setDomainEnv.cmd file) variable as below:
set EXT_POST_CLASSPATH=%EXT_POST_CLASSPATH%;%DOMAIN_HOME%\config\appConfig
You can access that file in you java code as below:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream ("config.properties");
Properties prop = new Properties();
prop.load(inputStream);
String value = prop.getProperty("key");
Hope this helps.
The most flexible way is to use weblogic deployment plans and Generic File Loading overrides
External properties file with Weblogic
http://docs.oracle.com/cd/E21764_01/web.1111/e13702/config.htm#DEPGD188
Although it may be a little extra effort, if you put the files into a JAR before dropping them into that lib directory, that should work.
You can look at your setDomainEnv.cmd (Windows) or setDomainEnv.sh (Unix/Linux) script in your domain files and see what locations are added in the CLASSPATH for your domain. Then just choose one folder and place the properties file there, if you want a specific location for your properties file just edit the script.
that was my solution:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
InputStream is = null;
String urlExte = System.getenv("DOMAIN_HOME")+"/properties/SmsBalanceadoWS/";
org.springframework.core.io.Resource resource = ctx.getResource( "file:"+urlExte+"/application.properties");
try {
is = resource.getInputStream();
} catch (IOException e) {
LOGGER.debug("ERROR"+ e.getMessage());
}