Java 读取外部资源的方法详解及实例代码
Java 读取外部资源的方法详解
在Java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下.
1.从当前的工作目录中读取:
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中读取(读取找到的第一个符合名称的文件):
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中遍历):
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中读取:
try {
URL url = new URL("http://blog.csdn.net/kkdelta");
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的类中使用):
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()是不同的,查找的路径不一样.
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章
Java零基础教程之Windows下安装、启动Tomcat服务器方法图解(免安装版)
这篇文章主要介绍了Windows系统下安装、启动、注册服务、停止 Tomcat操作的所有方法,本文通过图文并茂的方式给大家介绍的非常详细,感兴趣的朋友一起看看吧2016-09-09
Spring Boot整合流控组件Sentinel的场景分析
Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑,这篇文章主要介绍了Spring Boot整合流控组件Sentinel的过程解析,需要的朋友可以参考下2021-12-12
详解mybatis-plus的 mapper.xml 路径配置的坑
这篇文章主要介绍了详解mybatis-plus的 mapper.xml 路径配置的坑,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-08-08
SpringBoot 配置文件中配置的中文,程序读取出来是乱码的解决
这篇文章主要介绍了SpringBoot 配置文件中配置的中文,程序读取出来是乱码的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-09-09
Java实现过滤掉map集合中key或value为空的值示例
这篇文章主要介绍了Java实现过滤掉map集合中key或value为空的值,涉及java针对map的简单遍历、判断、移除等相关操作技巧,需要的朋友可以参考下2018-06-06


最新评论