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.
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.
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");
If I want to create a file in C:/a/b/test.txt, can I do something like:
File f = new File("C:/a/b/test.txt");
Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path, Paths, and Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}
I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.
Questions:
Do I need to store the file in the same package as the class which will load them, or is there any specific location where it should be placed?
Does the file need to end in any specific extension or is .txt OK?
How can I load the file in the code
And how can I iterate through the values inside?
You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
Iterate as:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
You can store the file anywhere you like. If you want to keep it in your jar file, you'll want to use Class.getResourceAsStream() or ClassLoader.getResourceAsStream() to access it. If it's on the file system it's slightly easier.
Any extension is fine, although .properties is more common in my experience
Load the file using Properties.load, passing in an InputStream or a StreamReader if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and a Reader instead of the default ISO-8859-1 encoding for a stream.)
Iterate through it as you'd iterate through a normal Hashtable (which Properties derives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().
If you put the properties file in the same package as class Foo, you can easily load it with
new Properties().load(Foo.class.getResourceAsStream("file.properties"))
Given that Properties extends Hashtable you can iterate over the values in the same manner as you would in a Hashtable.
If you use the *.properties extension you can get editor support, e.g. Eclipse has a properties file editor.
There are many ways to create and read properties files:
Store the file in the same package.
Recommend .properties extension however you can choose your own.
Use theses classes located at java.util package => Properties, ListResourceBundle, ResourceBundle classes.
To read properties, use iterator or enumerator or direct methods of Properties or java.lang.System class.
ResourceBundle class:
ResourceBundle rb = ResourceBundle.getBundle("prop"); // prop.properties
System.out.println(rb.getString("key"));
Properties class:
Properties ps = new Properties();
ps.Load(new java.io.FileInputStream("my.properties"));
This load the properties file:
Properties prop = new Properties();
InputStream stream = ...; //the stream to the file
try {
prop.load(stream);
} finally {
stream.close();
}
I use to put the .properties file in a directory where I have all the configuration files, I do not put it together with the class that accesses it, but there are no restrictions here.
For the name... I use .properties for verbosity sake, I don't think you should name it .properties if you don't want.
Properties has become legacy. Preferences class is preferred to Properties.
A node in a hierarchical collection of preference data. This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store.
Unlike properties which are String based key-value pairs, The Preferences class has several methods used to get and put primitive data in the Preferences data store. We can use only the following types of data:
String
boolean
double
float
int
long
byte array
To load the the properties file, either you can provide absolute path Or use getResourceAsStream() if the properties file is present in your classpath.
package com.mypack.test;
import java.io.*;
import java.util.*;
import java.util.prefs.Preferences;
public class PreferencesExample {
public static void main(String args[]) throws FileNotFoundException {
Preferences ps = Preferences.userNodeForPackage(PreferencesExample.class);
// Load file object
File fileObj = new File("d:\\data.xml");
try {
FileInputStream fis = new FileInputStream(fileObj);
ps.importPreferences(fis);
System.out.println("Prefereces:"+ps);
System.out.println("Get property1:"+ps.getInt("property1",10));
} catch (Exception err) {
err.printStackTrace();
}
}
}
xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="user">
<map />
<node name="com">
<map />
<node name="mypack">
<map />
<node name="test">
<map>
<entry key="property1" value="80" />
<entry key="property2" value="Red" />
</map>
</node>
</node>
</node>
</root>
</preferences>
Have a look at this article on internals of preferences store
Example:
Properties pro = new Properties();
FileInputStream in = new FileInputStream("D:/prop/prop.properties");
pro.load(in);
String temp1[];
String temp2[];
// getting values from property file
String username = pro.getProperty("usernamev3");//key value in prop file
String password = pro.getProperty("passwordv3");//eg. username="zub"
String delimiter = ","; //password="abc"
temp1=username.split(delimiter);
temp2=password.split(delimiter);
In order:
You can store the file pretty much anywhere.
no extension is necessary.
Montecristo has illustrated how to load this. That should work fine.
propertyNames() gives you an enumeration to iterate through.
By default, Java opens it in the working directory of your application (this behavior actually depends on the OS used). To load a file, do:
Properties props = new java.util.Properties();
FileInputStream fis new FileInputStream("myfile.txt");
props.load(fis)
As such, any file extension can be used for property file. Additionally, the file can also be stored anywhere, as long as you can use a FileInputStream.
On a related note if you use a modern framework, the framework may provide additionnal ways of opening a property file. For example, Spring provide a ClassPathResource to load a property file using a package name from inside a JAR file.
As for iterating through the properties, once the properties are loaded they are stored in the java.util.Properties object, which offer the propertyNames() method.
Reading a properties file and loading its contents to Properties
String filename = "sample.properties";
Properties properties = new Properties();
input = this.getClass().getClassLoader().getResourceAsStream(filename);
properties.load(input);
The following is the efficient way to iterate over a Properties
for (Entry<Object, Object> entry : properties.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
In Java 8 to get all your properties
public static Map<String, String> readPropertiesFile(String location) throws Exception {
Map<String, String> properties = new HashMap<>();
Properties props = new Properties();
props.load(new FileInputStream(new File(location)));
props.forEach((key, value) -> {
properties.put(key.toString(), value.toString());
});
return properties;
}
1) It is good to have your property file in classpath but you can place it anywhere in project.
Below is how you load property file from classpath and read all properties.
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "path to property file";
input = getClass().getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2) Property files have the extension as .properties
Here is another way to iterate over the properties:
Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) {
String key = (String) eProps.nextElement();
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
I have written on this property framework for the last year.
It will provide of multiple ways to load properties, and have them strongly typed as well.
Have a look at http://sourceforge.net/projects/jhpropertiestyp/
JHPropertiesTyped will give the developer strongly typed properties.
Easy to integrate in existing projects.
Handled by a large series for property types.
Gives the ability to one-line initialize properties via property IO implementations.
Gives the developer the ability to create own property types and property io's.
Web demo is also available, screenshots shown above.
Also have a standard implementation for a web front end to manage properties, if you choose to use it.
Complete documentation, tutorial, javadoc, faq etc is a available on the project webpage.
Here ready static class
import java.io.*;
import java.util.Properties;
public class Settings {
public static String Get(String name,String defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return props.getProperty(name);
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Integer Get(String name,Integer defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Integer.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Boolean Get(String name,Boolean defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Boolean.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static void Set(String name, String value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer, Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Integer value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Boolean value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
}
Here sample:
Settings.Set("valueName1","value");
String val1=Settings.Get("valueName1","value");
Settings.Set("valueName2",true);
Boolean val2=Settings.Get("valueName2",true);
Settings.Set("valueName3",100);
Integer val3=Settings.Get("valueName3",100);
You can load the property file suing the following way:
InputStream is = new Test().getClass().getClassLoader().getResourceAsStream("app.properties");
Properties props = new Properties();
props.load(is);
And then you can iterate over the map using a lambda expression like:
props.stringPropertyNames().forEach(key -> {
System.out.println("Key is :"+key + " and Value is :"+props.getProperty(key));
});
in my opinion other ways are deprecated when we can do it very simple as below:
#PropertySource("classpath:application.properties")
public class SomeClass{
#Autowired
private Environment env;
public void readProperty() {
env.getProperty("language");
}
}
it is so simple but i think that's the best way!!
Enjoy