java讀取存在src目錄下和存在同級目錄下的配置文件


如果我有個文件存在src下一級的地方和存在src同級的目錄應該怎么用相對路徑去獲取如圖:

 

一、如果存在src同級的地方應該是InputStream in = new BufferedInputStream(new FileInputStream("./set.properties"));就可以了。

代碼如下:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

public class PropertiesUtil {
public static String getUrlValue(String urlName) {
        String url = null;
        Properties prop = new Properties();
        try {
        //ConfigUtil.class.getClassLoader().getSystemClassLoader().getResource(""));
            ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 讀取屬性文件xxxxx.properties
            //InputStream in = classLoader.getResourceAsStream("config/config.properties");
            InputStream in = new BufferedInputStream(new FileInputStream("./set.properties"));
            prop.load(in); /// 加載屬性列表
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while (it.hasNext()) {
                if (it.next().equals(urlName)) {
                    url = prop.getProperty(urlName);
                }
            }
            in.close();
        } catch (Exception e) {
            
        }
        return url;
    }
}
配置文件如:

測試:

import cn.deos.util.PropertiesUtil;
public class test {
public static void main(String []args){

String urlValue = PropertiesUtil.getUrlValue("defaultFileDirectory");
System.out.println("urlValue=="+urlValue);
}
}
二 、如果存在src下一級的地方應該是ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 讀取屬性文件xxxxx.properties
            //InputStream in = classLoader.getResourceAsStream("set.properties");就可以了。

代碼如下:

import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
public class PropertiesUtil {
public static String getUrlValue(String urlName) {
        String url = null;
        Properties prop = new Properties();
        try {
            ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 讀取屬性文件xxxxx.properties
            InputStream in = classLoader.getResourceAsStream("config/config.properties");
            //InputStream in = new BufferedInputStream(new FileInputStream("set.properties"));
            prop.load(in); /// 加載屬性列表
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while (it.hasNext()) {
                if (it.next().equals(urlName)) {
                    url = prop.getProperty(urlName);
                }
            }
            in.close();
        } catch (Exception e) {
            
        }
        return url;
    }

}
測試如下:

import cn.deos.util.PropertiesUtil;
public class test {
public static void main(String []args){

String urlValue = PropertiesUtil.getUrlValue("defaultFileDirectory");
System.out.println("urlValue=="+urlValue);
}
}
 


免責聲明!

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



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