Java Properties file examples
Normally, Java properties file is used to store project configuration data or settings. In this tutorial, we will show you how to read and write to/from a properties file.
1. Write to properties file
Set the property value, and write it into a properties file named
config.properties
.
App.java
package com.mkyong.properties;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class App {
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();
}
}
}
}
}
Output
config.properties
#Fri Jan 17 22:37:45 MYT 2014
dbpassword=password
database=localhost
dbuser=mkyong
P.S If file path is not specified, then this properties file will be stored in your project root folder.
2. Load a properties file
Load a properties file from the file system and retrieved the property value.
App.java
package com.mkyong.properties;
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("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();
}
}
}
}
}
Output
localhost
mkyong
password
Không có nhận xét nào:
Đăng nhận xét