[go: up one dir, main page]

0% found this document useful (0 votes)
9 views5 pages

Java Properties File Handling Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

Java Properties File Handling Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

java.util.

Properties
examples
CSE219, Computer Science III
Stony Brook University
http://www.cs.stonybrook.edu/~cse219
java.util.Properties
 Java properties files are used to store project
configuration data or settings.
These can be .properties files or .xml files
Example: config.properties
#Fri March 6 12:32:35 MYT 2015
database=localhost
dbuser=paul
dbpassword=password
2
(c) Paul Fodor
import java.util.Properties;
import java.io.InputStream; Load a properties file
import java.io.FileInputStream;
import java.io.IOException;

public class ReadProperties {


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("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();
}
}
3 }
(c) Paul Fodor
}
import java.util.Properties;
import java.io.FileOutputStream; Write to properties file
import java.io.IOException;
import java.io.OutputStream;

public class WriteProperties {


public static void main(String[] args) {
public static void main(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("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);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}

4 }
(c) Paul Fodor
}
Also in XML: properties.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE properties SYSTEM
"http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="database">localhost</entry>
<entry key="dbuser">paul</entry>
<entry key="dbpassword">password</entry>
</properties>

In Java:
Properties properties = new Properties();
properties.loadFromXML(fileInput);

5
(c) Paul Fodor

You might also like