zoukankan      html  css  js  c++  java
  • Maven项目读取resources下文件的路径问题(getClassLoader的作用)

    读取resources下文件的方法

    网上有问答如下:
    问:
      new FileInputStream("src/main/resources/all.properties")
      new FileInputStream("./src/main/resources/all.properties")
      上面两个无法读取maven下资源文件目录下的文件嘛,总是提示找不到该路径,这么写错了嘛,但是我的其他maven可以读取

    答:
      要取编译后的路径,而不是你看到的src/main/resources的路径。如下:
      URL url = MyTest.class.getClassLoader().getResource("conf.properties");
      File file = new File(url.getFile());
      或者
      InputStream in = MyTest.class.getClassLoader().getResourceAsStream("conf.properties");

    第二种方法,也可以改成
      InputStream in = getClass().getClassLoader().getResourceAsStream("conf.properties");

    同事的一种的写法是:
      InputStream in = getClass().getResourceAsStream("conf.properties");
      然后怎么也获取不到,最后才发现,只要添加了.getClassLoader()就可以了

    getClassLoader() 的作用

      getClass():取得当前对象所属的Class对象
      getClassLoader():取得该Class对象的类装载器
      类装载器负责从Java字符文件将字符流读入内存,并构造Class类对象,在你说的问题那里,通过它可以得到一个文件的输入

    Class.getClassLoader()的一个小陷阱,空指针异常
      昨天我的code总在Integer.class.getClassLoader().getResource("*********");这一句抛出空指针异常,定位为getClassLoader()返回null,查了一下jdk的文档,原来这里还有一个陷阱:
      这里jdk告诉我们:如果一个类是通过bootstrap 载入的,那我们通过这个类去获得classloader的话,有些jdk的实现是会返回一个null的,比如说我用 new Object().getClass().getClassLoader()的话,会返回一个null,这样的话上面的代码就会出现NullPointer异常.所以保险起见我们最好还是使用我们自己写的类来获取classloader("this.getClass().getClassLoader()“),这样一来就不会有问题。

    参考链接:
    [1]http://www.oschina.net/question/2935586_2218431
    [2]http://blog.sina.com.cn/s/blog_6ec6be0e01011xof.html

  • 相关阅读:
    exec系列函数和system函数
    fork函数相关总结
    文件的内核结构file和dup实现重定向
    进程基本概述
    fcntl 函数与文件锁
    文件的属性
    目录的操作
    文件的读取写入
    文件的打开关闭
    浅谈原始套接字 SOCK_RAW 的内幕及其应用(port scan, packet sniffer, syn flood, icmp flood)
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/mavenResources.html
Copyright © 2011-2022 走看看