java 如何讀取src根目錄下的屬性文件


在java項目中,如何獲取src根目錄下的屬性文件/資源文件呢?

有如下三種方式:

方式一:

InputStream in = Test.class   
        .getResourceAsStream("/env.properties");  
URL url = Test.class.getResource("<span style="color: #000000;">/</span>env.properties")  ;  

 說明:env.properties文件在src的根目錄下,文件名前有斜杠

方式二:

InputStream in = Test.class.getClassLoader()    
      .getResourceAsStream("env.properties");  
URL url = Test.class.getClassLoader().getResource("env.properties")  ;  

 

方式三:

InputStream in = Thread.currentThread().getContextClassLoader()  
                .getResourceAsStream("ExcelModeMappingl.xml");  

 

 示例:

private Properties readConfig(){
InputStream in = this.getClass().getResourceAsStream("/config.properties");
// String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
// int lastIndex = path.lastIndexOf(File.separator) + 1;
// path = path.substring(0, lastIndex);
// File configFile = new File(path + "configration.properties");
// InputStream in = null;
// try
// {
// in = new FileInputStream(configFile);
// }
// catch (FileNotFoundException e)
// {
// e.printStackTrace();
// }

Properties props = new Properties();
InputStreamReader inputStreamReader = null;
try
{
inputStreamReader = new InputStreamReader(in, "UTF-8");
props.load(inputStreamReader);
}
catch (Exception e)
{
e.printStackTrace();
}
return props;
}
config.properties在src/main/resources目錄下
注釋掉的部分是讀取jar包平級目錄下的配置文件。有時需要把配置文件放在jar包外面方便配置,因此需要讀取jar包外的配置文件。

本地讀取資源文件

java類中需要讀取properties中的配置文件,可以采用文件(File)方式進行讀取:

1 File file = new File("src/main/resources/properties/basecom.properties");
2 InputStream in = new FileInputStream(file);

當在eclipse中運行(不部署到服務器上),可以讀取到文件。

服務器(Tomcat)讀取資源文件

采用流+Properties

當工程部署到Tomcat中時,按照上邊方式,則會出現找不到該文件路徑的異常。經搜索資料知道,Java工程打包部署到Tomcat中時,properties的路徑變到頂層(classes下),這是由Maven工程結構決定的。由Maven構建的web工程,主代碼放在src/main/java路徑下,資源放在src/main/resources路徑下,當構建為war包的時候,會將主代碼和資源文件放置classes文件夾下:

並且,此時讀取文件需要采用流(stream)的方式讀取,並通過JDK中Properties類加載,可以方便的獲取到配置文件中的信息,如下:

 InputStream in = this.getClass().getResourceAsStream("/properties/basecom.properties");
Properties properties = new Properties();
properties.load(in);
properties.getProperty("property_name");

 其中properties前的斜杠,相對於調用類,共同的頂層路徑。

 

 

 


免責聲明!

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



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