Properties getProperty returning null - java

I'm having the following problem. I'm using Java properties to read some info of a file, but when I call prop.getProperty("var") it returns null. I ran out of ideas. Here is the code I have.
static final Properties prop = new Properties();
public JConnection(){
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}
I never get the error message "file not found".
public static Connection getConnection(String conType) {
Connection conn;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
if(model == "client"){
conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("usr"),prop.getProperty("pass"));
}else{
conn = DriverManager.getConnection(prop.getProperty("url1"),prop.getProperty("usr1"),prop.getProperty("pass1"));
}
} catch (Exception ex) {
ex.printStackTrace();
conn = null;
}
When it tries to connect to the DB, getProperty is returning null as it is not found. Any ideas of what it could be or what I'm doing wrong?

Another wild guess: I noticed that both your prop variable and the method that's reading from it are static, so maybe you are using this as some sort of static utilities class without ever creating an instance of the class? In this case, you are never calling the constructor and never actually loading the properties file. Instead, you might try this:
static final Properties prop = new Properties();
static {
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}

You have a static field (prop), but you initialize it in a constructor. This means if you consult your prop object before you construct any object of JConnection, prop will not be initialized.
You can try something like this:
public class JConecction {
static final Properties prop = new Properties();
static {
try {
prop.load(new FileInputStream("db.properties"));
} catch(Exception e) {
logger.info("file not found.");
e.printStackTrace();
}
}
}

Related

How to read properties file from different location in JAVA

I have sourcehandler.java class which has the code
public class SourceHandler {
String PrpPath = null;
Properties prop = null;
public Properties loadConfigProperties() {
try {
System.out.println("Propertiess " +PrpPath );
InputStream in =new FileInputStream(new File(PrpPath ));
prop.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
and main method in a different class,
public static void main(String[] args) throws ParserConfigurationException,
Exception {
try {
SourceHandler conf = new SourceHandler();
conf.setProperties("C:/config.properties");
Properties p = conf.loadConfigProperties();
System.out.println("Done");
} catch (DOMException dome) {
// TODO: Add catch code
dome.printStackTrace();
}
Now, if i run the code , it shows null pointer exception at line , prop.load(in);
stack trace:
java.lang.NullPointerException
at DecryptEncryptSource.SourceHandler.loadConfigProperties(SourceHandler.java:98)
at DecryptEncryptSource.SourceHandler.updateCofigDestn(SourceHandler.java:151)
at DecryptEncryptSource.MainClass.main(MainClass.java:27)
First of all,
InputStream in =new FileInputStream(new File(Properties));
should better read
InputStream in =new FileInputStream(new File(propertyFileName));
to avoid any ambiguity; and then:
Are you sure that there is really a file named C:\config.properties
Probably you need either escaping: C:\\config.properties; or you try C:/config.properties
Regarding the update; you have this line:
Properties prop = null;
and further down:
prop.load(in);
And you are surprised that you get a NPE? Really? Hint: look into your code and create that Property object using the file path; instead of just calling a method on a null object.
And the real answer is read this here over and over again.
(and for those who wonder why I didn't close out as duplicate ... I can't any more, because I already close-requested on another reason )

How to load properties file which is in assets folder?

I'm working on an Android application and I need to read my properties in assets folder in /app/src/main/assets/app.properties.
But when I use:
Properties properties = new Properties();
try {
properties.load(new FileInputStream("app.properties"));
} catch (IOException e) {
...
}
The inputStream seems to be null. I think I have to precise the filepath or something like that to access to my properties file.
I need to use my properties in this class: /app/src/main/java/mypackage/model/myclass.java
You can load the propertiy file using your android context like this :
context.getAssets().open("app.properties");
For example in a Fragment :
try{
Properties properties = new Properties();
properties.load(this.getActivity().getAssets().open("app.properties"));
}catch(Exception e){
e.printStackTrace();
}
As you seem to need this in a class where the context is not accessible you can create your own application class with a static access to the context and then use this context everywhere.
Create your application class :
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance.getApplicationContext()
}
#Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
Add your new created application into the manifest :
<application
android:name="com.example.yourapp.MyApp"
...
Once this done you can load your properties in your XMLParser :
try{
Properties properties = new Properties();
properties.load(MyApp.getContext().getAssets().open("app.properties"));
}catch(Exception e){
e.printStackTrace();
}
Try getting the asset and them reading it:
AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
FileInputStream stream = fileDescriptor.createInputStream();
Properties properties = new Properties();
try {
properties.load(stream);
} catch (IOException e) {
...
}
In my unit tests "XMLParserTest" in /app/src/test/java/mypackage/XMLParserTest I tried with:
InputStream is = null;
Properties prop = null;
try {
prop = new Properties();
is = new FileInputStream(new File("C:/...fullpath.../app/src/main/assets/app.properties"));
prop.load(is);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
it works but when i put it in my XMLParser class my inputStream "is" is null.
It is like the class can't access to the file .properties. It works for tests only...
If you want to use a library: https://github.com/fernandodev/android-properties

Update properties file values with form values

I am having a jsp file in which I load the existing values present in properties file. When the user edit the existing value and submit the form, the properties file must be updated with that values. Can anyone help me with this? I am using only java.
FileInputStream in = new FileInputStream("Example.properties");
Properties props = new Properties();
props.load(in);
Now Update it
FileOutputStream outputStream = new FileOutputStream("Example.properties");
props.setProperty("valueTobeUpdate", "new Value");
props.store(outputStream , null);
outputStream .close();
Another way of achieving same is explained at
http://crunchify.com/java-properties-files-how-to-update-config-properties-file-in-java/
PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties");
config.setProperty("Name", "abcd");
config.setProperty("Email", "abcd#gmail.com");
config.setProperty("Phone", "123456");
config.save();
here is an example of how to update your properties file :
public class PropertyManager {
private static Properties prop = new Properties();
private static String PROPERTY_FILENAME = "config.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.get("myProperty"));
updateProperty("myProperty", "aSecondValue");
}
public static void loadProperty(){
InputStream input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(String name, String value){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty(name, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I let you change "new Properties", by the way you retrieve it.

Unable to read properties file after creating it

I am creating a properties file and putting into my classpath folder Resources.
When I tried to read this file , i am not getting the expected result. i am getting the result of the previous values printed instead of the property values set now.
My class file is as follows :
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
PrintWriter output = null;
try {
output = new PrintWriter("Resources/config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
if(output!=null) {
System.out.println("Output");
output.close();
}
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
Properties prop1 = new Properties();
BufferedInputStream input = null;
try {
String filename = "config.properties";
input = (BufferedInputStream) AppCPLoad.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop1.load(input);
//get the property value and print it out
System.out.println(prop1.getProperty("database"));
System.out.println(prop1.getProperty("dbuser"));
System.out.println(prop1.getProperty("dbpassword"));
if(input!=null) {
System.out.println("Input");
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Please help.
When you run the program, the properties file is loaded and the values are read. After you rewrite the properties file, that doesn't mean that the properties you have loaded already have be to rewritten. You need to reload the properties file and re-read the values. You are looking for an implementation like ReloadableResourceBundleMessageSource

Loading properites file using

Please look at the following code for a MSSQL Server 2005.
Properties File
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://127.0.0.1:1433;databaseName=LibMgmtSys
user=sa
password=passwrod
Connection File
public class DBConnection {
static Properties dbproperties;
public static Connection getConnection() throws Exception {
Connection conn = null;
InputStream dbInputStream = null;
dbInputStream = DBConnection.class.getResourceAsStream("jdbc.properties");
try {
dbproperties.load(dbInputStream);
Class.forName(dbproperties.getProperty("driver"));
conn = DriverManager.getConnection(dbproperties.getProperty("url"),
dbproperties.getProperty("user"),
dbproperties.getProperty("password"));
} catch (Exception exp) {
System.out.println("error : " + exp);
}
return conn;
}
}
The above code gives me a NullPointException when I try to do dbproperties.load(dbInputStream). Am I doing something wrong???
You didn't instantiate dbproperties, so it's null when you try to dereference it (dbproperties.load(dbInputStream);). Change it to:
try {
dbproperties = new Properties();
dbproperties.load(dbInputStream);

Categories