file路径正确但是找不到文件问题

//选择配置文件加载

  public Properties getProp(String code){

     try {

        File file = new File(this.getClass().getClassLoader().getResource("/").toURI().getPath()+"res");

        String[] fileName = file.list();

        String[] fname = new String[fileName.length];

        Properties prop = new Properties();

        for (int i = 0; i < fileName.length; i++) {

           fname[i] = fileName[i].substring(0,4);

           if(code.substring(1).equals(fname[i])){

              prop.load(this.getClass().getResourceAsStream("/res/"+fileName[i]));

           }

        }

        return prop;

     } catch (Exception e) {

        e.printStackTrace();

        returnnull;

     }

  }

问题是:

this.getClass().getClassLoader().getResource(“/”).getPath()+”res”

得到的路径如果有空格会把空格编译成%20,导致识别不了文件路径

解决办法:

getResource(“/”).toURI().getPath()

你可能感兴趣的:(java路径)