java 程序打包为jar发布后,读取配置文件路径出错 ,怎样获取配置文件路径?

如题所述

给你个例子,读取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;

}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-12-24
要把你的配置文件和class文件的路径放到一起,比如com.test,你要把application.xml什么的文件放到和com同一个文件夹里打包,不然一般会找不到的
第2个回答  2012-12-24
Class.getResourceAsStream(...文件路径、文件名...)
相似回答