FileNotFoundException when reading properties file - java

I am facing this issue while reading property file. I searched a lot on the Internet but nothing worked. Below is the code and the image contains the path of the prop.properties file
package Utility;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropUtility {
//private static Properties prop;
private static Properties prop = new Properties();
static {
prop = new Properties();
InputStream in = prop.getClass().getResourceAsStream("/resources/prop.properties");
try {
prop.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getProperty(String key) {
return prop.getProperty(key);
}
}

public static void main(String[] args) throws IOException {
FileReader reader= null;
try {
reader = new FileReader("prop.properties");
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}

When you run the code, it cannot access your properties file. You get a nullPointerException error when loading in from that one.
Get your properties file like in the picture below, put it in the project, then run your code. I also made a similar example with FileReader.
Extract from the resource folder. You can read it that way if you import it into the project.
Give this a try.

Related

config.properties file if not exist, how to pass a message in console and continue to next setup without throwing an exception

public static String readProperty(String property) {
Properties prop;
String value = null;
try {
prop = new Properties();
prop.load(new FileInputStream(new File("config.properties")));
value = prop.getProperty(property);
if (value == null || value.isEmpty()) {
throw new Exception("Value not set or empty");
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
I need to check if config.properties exist before loading - if not then just send soft warning message in console system.out.println("config.properties not found")
FileInputStream throws FileNotFoundException
if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
you can catch FileNotFoundException and print your soft warning. for example:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
public class PropTest
{
public static String readProperty(String property)
{
try (FileInputStream f = new FileInputStream(new File("config.properties"))) {
Properties prop = new Properties();
prop.load(f);
return prop.getProperty(property);
} catch (FileNotFoundException e) {
System.out.println("config.properties not found");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
String value = readProperty("foo.bar");
System.out.println(value);
value = readProperty("foo.baz");
System.out.println(value);
}
}
the method readProperty() now returns null if the property is not set or an error occurs while reading the properties file and it also prints a message if the file doesn't exists:
$ javac PropTest.java
$ java PropTest
config.properties not found
config.properties not found
$ echo "foo.bar=Hello world" > config.properties
$ java PropTest
Hello world
null
$
the line:
try (FileInputStream f = new FileInputStream(new File("config.properties"))) {
uses what is called a try-with-resources which automatically closes the file when the code has done with it.

Unable to read properties file from java

I am unable to read the properties from the file . When I try to print it gives me null, When I debugged I understood it is not loading the file in function
pro.Load(). However my path is correct, still I am unable to load the file
package AdvancedJava;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ReadingPropertiesFile {
public static void main(String[] args) throws FileNotFoundException {
Properties pro = new Properties();
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
// BufferedReader reader = new BufferedReader(new FileReader(path));
File f = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
pro.load(fis);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(pro.getProperty("lastname"));
}
}
Properties file contents
firstname = John
lastname = harry
Automation = Selenium
I think the problem is in path:
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
should be like this:
String path = "C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
Also make sure you have a correct path to your properties file. If it is inside your project, the path should be like this:
String path = "C:\\...\\ProjectFolder\\src\\main\\resources\\object.properties";
Your example works fine for me. Without a stacktrace though, we won't be able to help you regarding the NPE you're getting.
In any way though, I couple of hints regarding your code. I would suggest using a try - with resources when operating with the FileInputStream to make sure that the resource is going to be closed once done.
You can avoid using new File(path);. Instead I would suggest using Paths from the java.nio.* package. An example of this based on your code snippet would be the following:
public static void main(String[] args) {
Properties properties = new Properties();
try (FileInputStream stream = new FileInputStream(Paths.get("E:\\test\\file.txt").toFile())) {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(properties.getProperty("lastname"));
}
The advantage of using Paths is that they're (if not mistaken) system agnostic meaning that you won't need to worry about providing the proper path delimiters.
Actually, path should be with another separator
"C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
but what I should suggest you - it's to store your app properties files under your resource folder, kinda:
src/main/resources/config.properties
than you gonna be able to access this file like this:
public Properties extractFrom(String fileName) {
Properties properties = new Properties();
try (InputStream inputStream = PropertiesExtractor.class
.getClassLoader().getResourceAsStream(fileName)) {
properties.load(inputStream);
} catch (IOException ex) {
throw new RuntimeException("Cannot load properties", ex);
}
return properties;
}
extractFrom("config.properties");

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 set right path of property file?

I have a problem I can't resolve.
I need to read properties file, but can't set right path.
Documentation of java.io.File is saying that I have to set in from the src/...
It doesnt work, I did a path from current file and have the same problem.
EXCEPTION IS : FileNotFound
PropertyReader class:
public final class PropertyReader {
private Properties prop = new Properties();
private InputStream input = null;
public Properties getProperties(File file) {
try {
input = new FileInputStream(file);
// load a properties file
prop.load(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop;
}
}
And ApplicationController.class which uses PropertyReader:
#RequestMapping(value = "/result", method = RequestMethod.GET)
public String resultPage(ModelMap model) {
//Getting property with key "path"
model.addAttribute("path", new PropertyReader().getProperties(file).getProperty("path"));
return "result";
If I'm setting path from C://.. it works fine.
Thank you much and have a nice day!
Try to use Following example to read property file.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("mysqldb"));
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();
}
}
}
}
}
Its also depends on the framework that you are using like SpringMVC, JSF and Struts. All these framework have their own shortcut ways to access property files.
I resolved it by using annotations #PropertySource and #Value()
For example:
//There could be any folder
#PropertySource("classpath:file.properties")
public class AnyClass {
//There could be any property
#Value("${some.property}")
private String someValue;
}

How to write values in a properties file through java code

I have an issue.
I have a properties file. I want to store some values in that file and will implement in the code whenever it is required. Is there any way to do that?
I am using Properties class to do that..
Load the properties file using java.util.Properties.
Code snippet -
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("xyz.properties");
prop.load(in);
It provides Properties#setProperty(java.lang.String, java.lang.String) which helps to add new property.
Code snippet -
prop.setProperty("newkey", "newvalue");
This new set you can save using Properties#store(java.io.OutputStream, java.lang.String)
Code Snippet -
prop.store(new FileOutputStream("xyz.properties"), null);
You can do it in following way:
Set the properties first in the Properties object by using object.setProperty(String obj1, String obj2).
Then write it to your File by passing a FileOutputStream to properties_object.store(FileOutputStream, String).
Here is the example code :
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
class Main
{
static File file;
static void saveProperties(Properties p) throws IOException
{
FileOutputStream fr = new FileOutputStream(file);
p.store(fr, "Properties");
fr.close();
System.out.println("After saving properties: " + p);
}
static void loadProperties(Properties p)throws IOException
{
FileInputStream fi=new FileInputStream(file);
p.load(fi);
fi.close();
System.out.println("After Loading properties: " + p);
}
public static void main(String... args)throws IOException
{
file = new File("property.dat");
Properties table = new Properties();
table.setProperty("Shivam","Bane");
table.setProperty("CS","Maverick");
System.out.println("Properties has been set in HashTable: " + table);
// saving the properties in file
saveProperties(table);
// changing the property
table.setProperty("Shivam", "Swagger");
System.out.println("After the change in HashTable: " + table);
// saving the properties in file
saveProperties(table);
// loading the saved properties
loadProperties(table);
}
}
Your problem is not clear since Writing/reading from properties files is something already available in java.
To write to properties file you can use the Properties class as you mentioned :
Properties properties = new Properties();
try(OutputStream outputStream = new FileOutputStream(PROPERTIES_FILE_PATH)){
properties.setProperty("prop1", "Value1");
properties.setProperty("prop2", "Value2");
properties.store(outputStream, null);
} catch (IOException e) {
e.printStackTrace();
}
Source and more examples here
This work for me.
Properties prop = new Properties();
try {
InputStream in = new FileInputStream("src/loop.properties");
prop.load(in);
} catch (IOException ex) {
System.out.println(ex);
}
//Setting the value to our properties file.
prop.setProperty("LOOP", "1");
//Getting the value from our properties file.
String value = prop.getProperty("LOOP").trim();
try {
prop.store(new FileOutputStream("src/loop.properties"), null);
} catch (IOException ex) {
System.out.println(ex);
}

Categories