SpringBoot项目,resources目录下有一个配置文件cfca-config.properties,在代码中可以使用绝对路径和类路径去获取文件。
很奇怪的是:如果只new File,那么传进去什么路径都可以;
但若是new FileInputStream,那就只能传入绝对路径,传入相对路径就会报“ java.io.FileNotFoundException: classpath:cfca-config.properties (系统找不到指定的文件。)”的异常。
下面代码,将第二行屏蔽掉,正常运行;将第一行屏蔽掉(第二行放开)则会输出文件名然后报错。
public static void main(String[] args) throws FileNotFoundException {
File file = new File("E:\\IntelliJ IDEA 2019.2.4\\workspace\\WebDemo\\src\\main\\resources\\cfca-config.properties");
// File file = new File("classpath:cfca-config.properties");
System.out.println(file.getName());
FileInputStream fileInputStream = new FileInputStream(file);
}
根源在于FileInputStream中打开文件的方法open0()是native方法,可能底层写的时候无法正确获取到类路径下的文件。