Java獲取配置文件跟路徑


一直以為使用new File(相對路徑)可以讀取class目錄下的文件,其實不然。網上查詢了一些資料,弄清楚了原理,總結如下:

package com.coshaho.learn;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FilePathLearn
{
    public static void main(String[] args) throws IOException
    {
        // 方案1
        // 獲取代碼工程路徑,生產環境上只有class文件,沒有java文件與代碼工程,這種方式不可取
        File file = new File("");
        System.out.println(file.getCanonicalPath());
        
        // 方案2
        // 獲取代碼工程路徑,生產環境上使用會出現問題
        System.out.println(System.getProperty("user.dir")); 
        
        // 方案3
        // 獲取class文件根目錄(路徑中包含空格會被轉義為%20,此時new File會失敗)
        file = new File(FilePathLearn.class.getResource("/").getPath());
        System.out.println(file.getCanonicalPath());
        
        // 方案4
        // 獲取class文件目錄(路徑中包含空格會被轉義為%20,此時new File會失敗)
        file = new File(FilePathLearn.class.getResource("").getPath());
        System.out.println(file.getCanonicalPath());
        
        // 方案5
        // 可以看出來,這種方法的效果和方案3效果相同
        file = new File(FilePathLearn.class.getClassLoader().getResource("").getPath());
        System.out.println(file.getCanonicalFile()); 
        
        // 由於路徑可能包含空格,new file可能失敗,所以可以直接打開流讀取文件
        InputStream stream = FilePathLearn.class.getResource("CE_Excel.xml").openStream();
        InputStreamReader reader = new InputStreamReader(stream);
        BufferedReader bufReader=new BufferedReader(reader); 
        
        String str = null;
        while ((str = bufReader.readLine()) != null)
        {
            System.out.println(str);
        }
    }
}

 


免責聲明!

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



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