使用System.getProperty("user.dir")獲取項目下的文件內容


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM