在Java中读取配置文件如下方式:1、使用文件流和字符串流 import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ConfigReader { public static void main(String[] args) throws IOException { String filePath = "config.properties";BufferedReader br = ...
java如何读取配置文件?
在Java中读取配置文件如下方式:
1、使用文件流和字符串流
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ConfigReader {
public static void main(String[] args) throws IOException {
String filePath = "config.properties";
BufferedReader br = null;
String line;
String key = null;
String value = null;
try {
br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
if (line.startsWith("#") || line.trim().isEmpty()) {
continue;
}
int index = line.indexOf('=');
if (index != -1) {
key = line.substring(0, index).trim();
value = line.substring(index + 1).trim();
// 处理键值对
System.out.println(key + "=" + value);
}
}
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2、使用第三方库
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
public class ConfigReader {
public static void main(String[] args) {
Config config = ConfigFactory.load();
String username = config.getString("username");
String password = config.getString("password");
String databaseUrl = config.getString("databaseUrl");
System.out.println("Username: " + username);
System.out.println("Password: " + password);
System.out.println("Database URL: " + databaseUrl);
}
}2023-12-14
配置文件有很多类型,如果是文本文件的话,按格式可以分成XML, YAML, JSON等, 不同的格式有不同的读取方法。2023-12-05