给你个例子,读取config.properties文件。
文件内容(值自己加)如下:
TestHosts =
FormalHosts =
TestConfig =
FormalConfig =
HostsPath =
ConfigPath =
读取文件的类如下:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class EvnConfig{
public static Properties PROPERTIES = new Properties();
static{
String proFilePath = System.getProperty("user.dir")+"/config.properties";
//System.out.println(proFilePath);
//InputStream propertiesStream = EvnConfig.class.getClassLoader().getResourceAsStream(proFilePath);
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(proFilePath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
PROPERTIES.load(in);
}catch(IOException e){
System.out.println("properties创建失败!");
e.printStackTrace();
}
//System.out.println("EvnConfig.testHosts:"+PROPERTIES.getProperty("TestHosts"));
}
public static final String testHosts = changeCode(PROPERTIES.getProperty("TestHosts"));
public static final String formalHosts = changeCode(PROPERTIES.getProperty("FormalHosts"));
public static final String testConfig = changeCode(PROPERTIES.getProperty("TestConfig"));
public static final String formalConfig = changeCode(PROPERTIES.getProperty("FormalConfig"));
public static final String hostsPath = changeCode(PROPERTIES.getProperty("HostsPath"));
public static final String configPath = changeCode(PROPERTIES.getProperty("ConfigPath"));
public static String changeCode(String str){
String toStr = "";
try {
//System.out.println(str + "转换...");
toStr = new String(str.getBytes("ISO-8859-1"),"GB2312");
//System.out.println(str + "转换成功!");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println(str + "转换失败!");
e.printStackTrace();
}
return toStr;
}
}
要把你的配置文件和class文件的路径放到一起,比如com.test,你要把application.xml什么的文件放到和com同一个文件夹里打包,不然一般会找不到的
Class.getResourceAsStream(...文件路径、文件名...)
举例:
把配置文件ccc.xml放到编译路径,如src/com.aaa.aa下面,然后再根据
String rootPath=Xxxx.class.getResource("/").getPath();
获取到编译的根路径,配置文件的地址就是rootPath+"com/aaa/aa/ccc.xml"