| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 353 人关注过本帖
标题:JAVA读取外部资源的方法
只看楼主 加入收藏
huatainong
Rank: 1
等 级:新手上路
帖 子:13
专家分:0
注 册:2012-7-30
结帖率:0
收藏
 问题点数:0 回复次数:0 
JAVA读取外部资源的方法
在java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下.

1.从当前的工作目录中读取:

[java] view plaincopyprint?
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("wkdir.txt")));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
 
2,从classpath中读取(读取找到的第一个符合名称的文件):

[java] view plaincopyprint?
try {
InputStream stream = ClassLoader.getSystemResourceAsStream("fileinjar.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
 
3,从classpath中读取(读取找到的所有符合名称的文件,如Spring中带有classpath*:前缀的情况就会从classpath中遍历):

[java] view plaincopyprint?
try {

Enumeration resourceUrls = Thread.currentThread().getContextClassLoader().getResources("fileinjar.txt");

while (resourceUrls.hasMoreElements()) {
URL url = (URL) resourceUrls.nextElement();
System.out.println(url);

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();

}

} catch (IOException e) {
}
 
4,从URL中读取:

[java] view plaincopyprint?
try {

URL url = new URL("http://blog.);
System.out.println(url);

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();

} catch (IOException e) {
e.printStackTrace();
}
 
5,web项目从web-inf文件夹读取(通过得到ServletContext读取,可以在servlet或者能够得到request的类中使用):

[java] view plaincopyprint?
try {

URL url = (URL) getServletContext().getResource("/WEB-INF/webinffile.txt");
// URL url = (URL)req.getSession().getServletContext().getResource("/WEB-INF/webinffile.txt");
System.out.println(url);

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();

} catch (IOException e) {
e.printStackTrace();
}
 
以上代码在eclipse环境中运行测试过.不过最近在用JUnit的时候,通过ant运行JUnit时通过ClassLoader.getSystemResourceAsStream("file.txt");的方式去找不到文件.改成 Xclass.class.getClassLoader().getResourceAsStream("file.txt");能从ant指定的classpath中找到文件.原因是ClassLoader和Xclass.class.getClassLoader()是不同的,查找的路径不一样.www.
2012-08-01 17:24
快速回复:JAVA读取外部资源的方法
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019240 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved