In Java, configuration files generally come in two forms: xml files or PRperty files. But most people are accustomed to using ini files, and the sectioning and annotation functions of ini files are easier to understand and use than XML.
There are standard functions for reading and writing ini files in the vc class library. In Dephi or other languages, you can also use Windows API functions to read and write INI files. But there seems to be no ready-made classes and methods available in java. Although Java can call the Windows API by loading dll files, it always feels not authentic enough.
So I wrote a class for reading and writing ini configuration files for your reference.
package mytools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader; util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This is a configuration file operation class, used to read and set ini configuration files
* @author by month
* @version 2004-08-18
*/
public final class ConfigurationFile {
/**
* Read the value of the variable from the ini configuration file
* @param file The path to the configuration file
* @param section The section name of the variable to be obtained
* @param variable The variable name to be obtained
* @param defaultValue The variable name The default value when it does not exist
* @return The value of the variable
* @throws IOException Throws io exceptions that may occur in file operations
*/
public static String getProfileString(
String file ,
String section,
String variable,
String defaultValue)
throws IOException {
String strLine, value = "";
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
boolean isInSection = false;
try {
while ((strLine = bufferedReader.readLine()) != null) {
strLine = strLine.trim();
strLine = strLine.split("[;]")[0];
Pattern p;
Matcher m;
p = Pattern.compile("file://[//s*.*//s*//]");
m = p.matcher((strLine));
if (m.matches()) {
p = Pattern.compile("file://[//s*" + section + "file://s*//]");
m = p.matcher(strLine);
if (m. matches()) {
isInSection = true;
} else {
isInSection = false;
}
}
if (isInSection == true) {
strLine = strLine.trim();
String[] strArray = strLine.split ("=");
if (strArray.length == 1) {
value = strArray[0].trim();
if (value.equalsIgnoreCase(variable)) {
value = "";
return value;
}
} else if (strArray.length == 2) {
value = strArray[0].trim();
if (value.equalsIgnoreCase(variable)) {
value = strArray[1].trim();
return value;
}
} else if (strArray.length > 2) {
value = strArray[0].trim();
if (value.equalsIgnoreCase(variable)) {
value = strLine.substring(strLine .indexOf("=") + 1).trim();
return value;
The above is the content of reading and writing ini configuration files using java. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!