//读取配置文件//方法一InputStream in= this.getClass().getResourceAsStream("aa.properties");Properties pr = new Properties();try{pr.load(in);String value = pr.getProperty("key");}catch(Exception e){}//方法二ResourceBundle rb = null;rb.getBundle("aa");//这里不要后缀名String va =rb.getString("key");
Java几种加载文件路经的方式
得到src下的aa.porperties文件
ResourceBundle localResource = ResourceBundle.getBundle(“aa”);
得到src下com.svse下包下的aa.propertes文件
ResourceBundle localResource = ResourceBundle.getBundle("com/svse",”aa”);
String value = localResource.getString("test");System.out.println("ResourceBundle: " + value);
工程src目录下aa.properties(名字后缀必须为properties)文件内容如下:
test=hello word
相对路径的获得说明:相对路径(即不写明时候到底相对谁)均可通过以下方式获得(不论是一般的java项目还是web项目)String relativelyPath=System.getProperty("user.dir");上述相对路径中,java项目中的文件是相对于项目的根目录web项目中的文件路径视不同的web服务器不同而不同(tomcat是相对于 tomcat安装目录\bin)
类加载目录的获得
1.1)通用的方法一(不论是一般的java项目还是web项目,先定位到能看到包路径的第一级目录)
InputStream is= Thread.currentThread().getContextClassLoader().
.getResourceAsStream("test.txt");(test.txt文件的路径为 项目名\src\test.txt)
1.2)通用方法二 (此方法和1.1中的方法类似,不同的是此方法必须以'/'开头)InputStream is= this.getClass()..getResourceAsStream("/test.txt");(test.txt文件的路径为 项目名\src\test.txt,类Test1所在包的第一级目录位于src目录下)
1.3) 得到工程 所在的目录
URL url = this.getClass().getResource("/");
if(url == null){
url = Thread.currentThread()
.getContextClassLoader().getResource("/");
}
try{
File file = new File(url.getFile());
//得到classes目录所在的路径
//如:E:\workspacesFlex\tomcat6.0\webapps\ssh\WEB-INF\classes
String classPath = file.getPath();
System.out.println(classPath);
//向上返回两级得到工程 所在的跟路径 如:
//E:\workspacesFlex\tomcat6.0\webapps\ssh
srcPath = file.getParentFile().getParent();
System.out.println(srcPath);
}catch(Exception e){
System.out.println("得到文件路径出错");
}