Java 读取外部资源的方法详解及实例代码
Java读取外部资源的方法详解
在Java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下.
1.从当前的工作目录中读取:
try{
BufferedReaderin=newBufferedReader(newInputStreamReader(newFileInputStream("wkdir.txt")));
Stringstr;
while((str=in.readLine())!=null){
System.out.println(str);
}
in.close();
}catch(IOExceptione){
}
2,从classpath中读取(读取找到的第一个符合名称的文件):
try{
InputStreamstream=ClassLoader.getSystemResourceAsStream("fileinjar.txt");
BufferedReaderin=newBufferedReader(newInputStreamReader(stream));
Stringstr;
while((str=in.readLine())!=null){
System.out.println(str);
}
in.close();
}catch(IOExceptione){
}
3,从classpath中读取(读取找到的所有符合名称的文件,如spring中带有classpath*:前缀的情况就会从classpath中遍历):
try{
EnumerationresourceUrls=Thread.currentThread().getContextClassLoader().getResources("fileinjar.txt");
while(resourceUrls.hasMoreElements()){
URLurl=(URL)resourceUrls.nextElement();
System.out.println(url);
BufferedReaderin=newBufferedReader(newInputStreamReader(url.openStream()));
Stringstr;
while((str=in.readLine())!=null){
System.out.println(str);
}
in.close();
}
}catch(IOExceptione){
}
4,从URL中读取:
try{
URLurl=newURL("http://blog.csdn.net/kkdelta");
System.out.println(url);
BufferedReaderin=newBufferedReader(newInputStreamReader(url.openStream()));
Stringstr;
while((str=in.readLine())!=null){
System.out.println(str);
}
in.close();
}catch(IOExceptione){
e.printStackTrace();
}
5,web项目从web-inf文件夹读取(通过得到ServletContext读取,可以在servlet或者能够得到request的类中使用):
try{
URLurl=(URL)getServletContext().getResource("/WEB-INF/webinffile.txt");
//URLurl=(URL)req.getSession().getServletContext().getResource("/WEB-INF/webinffile.txt");
System.out.println(url);
BufferedReaderin=newBufferedReader(newInputStreamReader(url.openStream()));
Stringstr;
while((str=in.readLine())!=null){
System.out.println(str);
}
in.close();
}catch(IOExceptione){
e.printStackTrace();
}
以上代码在eclipse环境中运行测试过.不过最近在用JUnit的时候,通过ant运行JUnit时通过ClassLoader.getSystemResourceAsStream("file.txt");的方式去找不到文件.改成Xclass.class.getClassLoader().getResourceAsStream("file.txt");能从ant指定的classpath中找到文件.原因是ClassLoader和Xclass.class.getClassLoader()是不同的,查找的路径不一样.
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!