这是最基本的三种java读取properties配置文件的操作,不包含与servlet,spring集成的方式
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
public class Test {
public static void main(String[] args){
//1. File方式读取properties,路径不好找,不建议使用
File pwd = new File("");
System.out.println("current directory: "+pwd.getAbsolutePath());
Properties prop = new Properties();
try {
prop.load(new FileInputStream("src/log4j.properties"));
System.out.println(prop.getProperty("log4j.rootCategory"));
} catch(IOException e) {
e.printStackTrace();
}
//2. classloader的getResourceAsStream,适用于本地类库等等配置
Properties prop2 = new Properties();
try {
prop2.load(Test.class.getClassLoader().getResourceAsStream("log4j.properties"));
System.out.println(prop2.getProperty("log4j.rootCategory"));
} catch(IOException e) {
e.printStackTrace();
}
//3. URL可以用网络等多种方式读取远程文件,适用于复杂场景的项目使用
String fileName = "log4j.properties";
Properties prop3 = new Properties();
//可以判断文件是否存在
URL fileUrl = Test.class.getClassLoader().getResource(fileName);
if (fileUrl == null){
throw new FileNotFoundException(fileName);
}
try {
//prop3.load(fileUrl.openStream());
//openConnection(proxy)可以设置DIRECT,HTTP,SOCKS
prop3.load(fileUrl.openConnection().getInputStream());
System.out.println(prop3.getProperty("log4j.rootCategory"));
} catch(IOException e) {
e.printStackTrace();
}
}
}