java读取配置文件
package com.rj.newservice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Properties;
public class PropertiesTest {
private static final String CONFIG_FILE_NAME="attr.properties";
private static Properties p=new Properties();
static String path=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
path=PropertiesTest.class.getResource("/").getPath()+CONFIG_FILE_NAME;
try {
path=URLDecoder.decode(path,"utf-8");
p.load(new FileInputStream(new File(path)));
System.out.println(p.getProperty("TelephoneNumber"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#文件样式
#默认电话号码
TelephoneNumber=021-12346667
但是这种读取方式会导致中文乱码,由于文件输入流不能识别编码格式,通过字符流就可以解决中文乱码问题
Properties properties = new Properties();
InputStream inputStream = this.getClass().getResourceAsStream("/attr.properties");
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));