Properties in java using Try-with-resources

arguments and properties into the application.
we can loop through String[] args from Main method, or we can process the properties object and persist them in order to use them out of execution scope.

below is the way using try-with-resources.


package com.navid.training.properties;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
*
* @author Navid
*/
public class PracticeProperties {

public static final Properties prop = new Properties();

public PracticeProperties() {
//init the sample
PracticeProperties.prop.setProperty("propertyKey1", "propertyValue1");
prop.setProperty("propertyKey2", "propertyValue2");
prop.setProperty("key1", "value1");
//        prop.setProperty("key1", null); // -- value canot be null

}

/**
* write into simple regular properties file.
*
* @param filename
* @throws IOException
*/
public void writeIntoPropertiesFile(String filename, Properties prop) throws IOException {

try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filename))) {
prop.store(writer, "my comment for this simple properties file.");

}

}

/**
* write properties into XML file.
*
* @param filename
* @throws IOException
*/
public  void writeIntoPropertiesXMLFile(String filename, Properties prop) throws IOException {
try (OutputStream out = Files.newOutputStream(Paths.get(filename))) {
prop.storeToXML(out, "my comment for this simple properties file.");
}
}

/**
* reading from single regular file.
*
* @param filename
* @throws IOException
*/
public  Properties readFromPropertiesFile(String filename) throws IOException {

Properties p = new Properties();

if (!Files.exists(Paths.get(filename))) {
System.out.println("File is not existed. - " + filename);
return null;
}

try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) {
p.load(reader);

}

return p;
}

public  Properties readFromPropertiesXMLFile(String filename) throws IOException {
Properties p = new Properties();

if (!Files.exists(Paths.get(filename))) {
System.out.println("File is not existed. - " + filename);
return null;
}

try (InputStream in = Files.newInputStream(Paths.get(filename))) {
p.loadFromXML(in);

}

return p;
}

}

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s