System.getProperty("user.dir")的作用是获取到项目所在的绝对路径,使用这个api就能获取项目下的文件
例如我想获取项目下/src/main/resources/config/certificate.properties的内容,可以使用如下代码:
public static Properties getProperties(String pathInDemo) throws IOException { Properties properties = new Properties(); String path = System.getProperty("user.dir") + "/src/main/resources/" + pathInDemo; File file = new File(path); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(file)); properties.load(bufferedReader); } catch (IOException e) { e.printStackTrace(); } return properties; } public static void main(String[] args) throws IOException { System.out.println("libreoffice.path=" + getConfig("config\certificate.properties", "libreoffice.path")); System.out.println( "certificate.image.suffix=" + getConfig("config\certificate.properties", "certificate.image.suffix")); }
以这样拼接路径的方式得到项目下指定文件的绝对路径,需要注意的是,System.getProperty("user.dir")获取到的项目路径以项目名称结尾,不带"/"。