maven下读取资源文件的问题(转)

原文链接:http://shenchao.me/2016/04/20/maven%E4%B8%8B%E8%AF%BB%E5%8F%96%E8%B5%84%E6%BA%90%E6%96%87%E4%BB%B6%E7%9A%84%E9%97%AE%E9%A2%98/

新建一个maven工程后,main目录下会有java和resources两个文件夹,其中java文件夹下存放源代码,resources文件夹下存放一些配置文件等。

在弄清楚编译后,资源文件以及字节码存在哪里这个问题之前,有必要明白什么是classpath

classpath实际上就是编译后的 以 classes 文件夹为起点的路径,而在ItelliJ IDEA 中编译后的文件都会存入target/classes下

所以,编译后,resources文件夹中的文件以及java目录下的文件都会存入同一个目录(target/classes)下,也就是说,编译后是不存在java和resources这两个目录的。

读取资源文件的若干中方法

package me.songfeng.main;

import java.io.BufferedReader;
import java.io.FileReader;

/**
 * Created by songfeng on 16/10/15.
 */
public class Demo1 {
    private static void readTxt(String filePath){
        BufferedReader reader =null;
        try{
            reader = new BufferedReader(new FileReader(filePath));
            String line = null;
            while((line = reader.readLine())!= null){
                System.out.println(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                try{
                    reader.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        // 获取classpath路径
        System.out.println("classpath路径: " + Demo1.class.getClassLoader().getResource("").getPath());

        // 获取当前类的加载路径
        System.out.println("当前类加载路径: " + Demo1.class.getResource("").getPath());

        readTxt(Demo1.class.getClassLoader().getResource("test/demo1.txt").getPath());

        readTxt(Demo1.class.getResource("/test/demo1.txt").getPath());

        readTxt(Demo1.class.getResource("../../../test/demo1.txt").getPath());
    }

}

其中,demo1.txt文件中的内容为:

hahahaha

输出如下:

classpath路径: /Users/songfeng/Work/mavendemo/target/classes/
当前类加载路径: /Users/songfeng/Work/mavendemo/target/classes/me/songfeng/main/
hahahaha
hahahaha
hahahaha

Process finished with exit code 0

从上面可以发现getResource 与 class.getClassLoader().getResource 两者的区别:

  1. 前者获取的是当前类加载的路径,如果用此方法读取文件则有两种方法,与相对路径绝对路径非常类似,具体参见代码
  2. 后者获取的是类加载器的路径,即会到classpath路径下。可以理解当前在 classp/ 目录下,要想访问哪个文件,直接填写路径即可,不用区分相对路径和绝对路径。显然,此方法比较容易写出。推荐。

 读取配置文件,可以参照下面这种方式:

  /**
   * Find, read, and parse the configuration file.
   * @return the properties that were found or empty if no file was found
   */
  private static Properties readConfigFile() {
    Properties properties = new Properties();

    //Get property file stream from classpath
    InputStream inputStream = Configuration.class.getClassLoader().getResourceAsStream(CONFIG_FILE);

    if (inputStream == null) {
      throw new RuntimeException(CONFIG_FILE + " not found in classpath");
    }

    // load the properties
    try {
      properties.load(inputStream);
      inputStream.close();
    } catch (FileNotFoundException fnf) {
      LOG.info("No configuration file " + CONFIG_FILE + " found in classpath.", fnf);
    } catch (IOException ie) {
      throw new IllegalArgumentException("Can't read configuration file " +
          CONFIG_FILE, ie);
    }

    return properties;
  }
原文地址:https://www.cnblogs.com/hubavyn/p/5964653.html