config.properties:
#读取配置文件的一种方法
username=hello
password=world
Config.java:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import org.apache.log4j.Logger;
public class Config {
public static Logger logger = Logger.getLogger(Config.class);
public static String username;
public static String password;
static {
load();
}
private static void load() {
String configFile = Config.class.getResource("/").getPath().toString().replaceAll("file:/", "") + "config.properties";
Properties p = new Properties();
try {
InputStreamReader inputStream = new InputStreamReader(new FileInputStream(configFile), "utf-8");
p.load(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(configFile);
username = p.getProperty("username");
password = p.getProperty("password");
}
}
TestConfig.java:
public class TestConfig {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(Config.username + "-" + Config.password);
}
}
config.properties文件要放在“项目名/WebRoot/WEB-INF/classes/”下面,有变动的话做相应的修改。