JAVA读取外部资源的方法

本文介绍了六种在Java中读取资源文件的方法,包括从工作目录、类路径、URL及Web项目的不同位置读取文件,并展示了如何解析JSON配置。
在java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下.
1.从当前的工作目录中读取:
[java]   view plain   copy
  1. try {  
  2.             BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("wkdir.txt")));  
  3.             String str;  
  4.             while ((str = in.readLine()) != null) {  
  5.                 System.out.println(str);  
  6.             }  
  7.             in.close();  
  8.         } catch (IOException e) {  
  9.         }  
2,从classpath中读取(读取找到的第一个符合名称的文件):
[java]   view plain   copy
  1. try {  
  2.             InputStream stream = ClassLoader.getSystemResourceAsStream("fileinjar.txt");  
  3.             BufferedReader in = new BufferedReader(new InputStreamReader(stream));  
  4.             String str;  
  5.             while ((str = in.readLine()) != null) {  
  6.                 System.out.println(str);  
  7.             }  
  8.             in.close();  
  9.         } catch (IOException e) {  
  10.         }  
3,从classpath中读取(读取找到的所有符合名称的文件,如Spring中带有classpath*:前缀的情况就会从classpath中遍历):
[java]   view plain   copy
  1. try {  
  2.   
  3.             Enumeration resourceUrls = Thread.currentThread().getContextClassLoader().getResources("fileinjar.txt");  
  4.   
  5.             while (resourceUrls.hasMoreElements()) {  
  6.                 URL url = (URL) resourceUrls.nextElement();  
  7.                 System.out.println(url);  
  8.   
  9.                 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));  
  10.                 String str;  
  11.                 while ((str = in.readLine()) != null) {  
  12.                     System.out.println(str);  
  13.                 }  
  14.                 in.close();  
  15.   
  16.             }  
  17.   
  18.         } catch (IOException e) {  
  19.         }  
4,从URL中读取:
[java]   view plain   copy
  1. try {  
  2.   
  3.             URL url = new URL("http://blog.youkuaiyun.com/kkdelta");  
  4.             System.out.println(url);  
  5.   
  6.             BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));  
  7.             String str;  
  8.             while ((str = in.readLine()) != null) {  
  9.                 System.out.println(str);  
  10.             }  
  11.             in.close();  
  12.   
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         }  
5,web项目从web-inf文件夹读取(通过得到ServletContext读取,可以在servlet或者能够得到request的类中使用):
[java]   view plain   copy
  1. try {  
  2.   
  3.             URL url = (URL) getServletContext().getResource("/WEB-INF/webinffile.txt");  
  4.             // URL url = (URL)req.getSession().getServletContext().getResource("/WEB-INF/webinffile.txt");  
  5.             System.out.println(url);  
  6.   
  7.             BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));  
  8.             String str;  
  9.             while ((str = in.readLine()) != null) {  
  10.                 System.out.println(str);  
  11.             }  
  12.             in.close();  
  13.   
  14.         } catch (IOException e) {  
  15.             e.printStackTrace();  
  16.         }  
 以上代码在eclipse环境中运行测试过.不过最近在用JUnit的时候,通过ant运行JUnit时通过ClassLoader.getSystemResourceAsStream("file.txt");的方式去找不到文件.改成 Xclass.class.getClassLoader().getResourceAsStream("file.txt");能从ant指定的classpath中找到文件.原因是ClassLoader和Xclass.class.getClassLoader()是不同的,查找的路径不一样.

6.项目中看到的 ,可以将格式json格式的文件转换成对象,然后在取值
      InputStream src = H4csUtil. class .getResourceAsStream( "/dsRouter.json" );
      MappingIterator<DsRouterRec> iter = new ObjectMapper().reader(DsRouterRec. class )
          .readValues( src );
      while ( iter .hasNext()) {
        DsRouterRec rec = iter .next();
        if ( rec .getCat() != null && rec .getCat().equals(H4csConstants. CENTER )) {
          if ( rec .getStorecodes() != null && rec .getStorecodes().contains( storeCode )) {
            return true ;
          }
        }
      }
      return false ;

dsRouter.json文件[
       {
             "cat" : "CENTER" ,
             "url" : "*********8" ,
             "username" : "h4cs" ,
             "password" : "h4cs" ,
             "storecodes" : [
                   "0103" ,
                   "0105" ,
                   "0106"
             ]
       },
       {
             "cat" : "HDPOS" ,
             "url" : "**************" ,
             "username" : "h4cs" ,
             "password" : "h4cs" ,
             "storecodes" : [
                   "0104"
             ]
       }
]

### Java读取外部资源文件的方法 #### 使用 `ClassLoader` 和 `FileSystemResource` 对于位于 jar 包之外的配置文件,可以通过 `ClassLoader` 或者 Spring 提供的 `FileSystemResource` 来访问这些文件。当使用 `ClassLoader.getSystemResourceAsStream()` 时,该方法适用于加载类路径下的资源[^1]。 然而,如果目标是读取绝对路径或相对路径指定的外部文件,则应考虑采用不同的策略。例如,在 Spring Boot 应用程序中,可以利用 `FileSystemResource` 类来指向具体的文件位置: ```java import org.springframework.core.io.FileSystemResource; public class ExternalConfigReader { public static void main(String[] args) throws Exception { FileSystemResource resource = new FileSystemResource("/path/to/your/config/file.yaml"); try (var reader = new java.io.BufferedReader(new java.io.InputStreamReader(resource.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } } } ``` 这段代码展示了如何通过给定的具体路径创建 `FileSystemResource` 实例并从中获取输入流以逐行打印文件内容[^3]。 #### 利用 `@PropertySource` 注解 另一种常见的方式是在基于 Spring 的应用里借助于 `@PropertySource` 注解配合 `Environment` 接口来动态载入属性文件中的键值对。这种方式特别适合管理应用程序的各种设置参数。下面是一个简单的例子说明怎样定义一个带有自定义配置文件的应用组件[^4]: ```java @Configuration @PropertySource("file:/absolute/path/to/application.properties") public class AppConfig { @Autowired private Environment env; @Bean public MyService myService() { MyService service = new MyServiceImpl(); service.setSomeProperty(env.getProperty("some.property.name")); return service; } } ``` 这里的关键在于 `@PropertySource` 可接受 file URL 方式的字符串作为参数,从而允许直接引用磁盘上的任意位置存储的 .properties 文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值