设为首页  |  加入收藏   |  点击咨询   
乘车路线
乘坐6,966,k906等公交车到文化路双铺路下车即可
咨询电话
招生咨询电话:0371-63383521 0371-63383522
学校地址:郑州市文化路90号河南财经政法大学文南1号楼
您当前所在的位置是:首页 > 专业介绍 > 软件
JAVA读取外部资源的方法有哪些?
发布时间:2019-07-09 10:14:38 来源:安阳计算机学校 作者:安阳计算机学校

java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下.
1.从当前的工作目录中读取:达内就业
[java] view plaincopyprint?

try { 

1. BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("wkdir.txt"))); String str; 

2. 
while ((str = in.readLine()) != null) { System.out.println(str); 

3. } in.close(); 

4. } catch (IOException e) { 

5. 
2,从classpath中读取(读取找到的第一个符合名称的文件):达内培训费用
[java] view plaincopyprint?

try { 

1. InputStream stream = ClassLoader.getSystemResourceAsStream("fileinjar.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(stream)); 

2. String str; 
while ((str = in.readLine()) != null) { 

3. System.out.println(str); } 

4. in.close(); } catch (IOException e) { 

5. 
3,从classpath中读取(读取找到的所有符合名称的文件,如Spring中带有classpath*:前缀的情况就会从classpath中遍历):
[java] view plaincopyprint?

try { 

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

2. 
while (resourceUrls.hasMoreElements()) { 

3. URL url = (URL) resourceUrls.nextElement(); System.out.println(url); 

4. 
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 

5. String str; 
while ((str = in.readLine()) != null) { 

6. System.out.println(str); } 

7. in.close(); 

8. 

9. } catch (IOException e) { 

10. }  
4,从URL中读取:达内怎么样
[java] view plaincopyprint?

try { 

1. 
URL url = new URL("http://blog.csdn.net/kkdelta"); 

2. System.out.println(url); 

3. BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; 

4. 
while ((str = in.readLine()) != null) { System.out.println(str); 

5. } in.close(); 

6. 
} catch (IOException e) { 

7. e.printStackTrace(); 

8. 
5,web项目从web-inf文件夹读取(通过得到ServletContext读取,可以在servlet或者能够得到request的类中使用):
[java] view plaincopyprint?

try { 

1. 
URL url = (URL) getServletContext().getResource("/WEB-INF/webinffile.txt"); 

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

3. 
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 

4. String str; 
while ((str = in.readLine()) != null) { 

5. System.out.println(str); } 

6. in.close(); 

7. } catch (IOException e) { e.printStackTrace(); 

8. 
以上代码在eclipse环境中运行测试过.不过最近在用JUnit的时候,通过ant运行JUnit时通过ClassLoader.getSystemResourceAsStream("file.txt");的方式去找不到文件.改成 Xclass.class.getClassLoader().getResourceAsStream("file.txt");能从ant指定的classpath中找到文件.原因是ClassLoader和Xclass.class.getClassLoader()是不同的,查找的路径不一样.

上一篇:java开发工具有哪些?具体详细介绍是什么? 下一篇:现在学习java怎么样?有什么好的发展方向吗?
安阳电脑学校 | 安阳计算机学校 | 计算机培训学校 | 电脑培训学校 | 在线咨询 | 网站地图|郑州北大青鸟
Copyright @ 2010-2023 安阳计算机学校-河南北大青鸟翔天信鸽IT培训学校 All Rights Reserved 版权所有
安阳电脑培训学校招生电话:152-251-91462