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")獲取到的項目路徑以項目名稱結尾,不帶"/"。