Java中如何去读取resources.properties文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a913858/article/details/82769869

今天迁移邮件管理功能的时候,有个图片上传功能,有个访问路径是在resources.properties配置,这个项目没有配置就找不到了。

正好发现了这个问题,就把读取resource配置文件的方法提供给大家。

package com.bonatone.knowledge.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ResourcesUtil {
	
	public static String getProperties(String name){
		Properties props = getPropertiesInCache();
		String value = props.getProperty(name); 
		return value;
	}
	
    public static Properties getPropertiesInCache() throws SecurityException {
    	Properties pro = null;
    	if(pro == null){
    		pro = getProperties();
    	}
        return pro;
    }
    
    private static Properties getProperties(){
		try { 
			InputStream in = Thread.currentThread().getContextClassLoader().getResource("resources.properties").openStream();
			Properties props = new Properties();
			props.load(in); 
			in.close(); // 别忘了关流 
			return props;
		} catch (FileNotFoundException e) { 
			e.printStackTrace(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
    }
    
    public static void putPropertiesToCache(){
    	Properties pro = getProperties();
    }
}

最常用读取properties文件的方法
InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:
InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");
Java中获取路径方法
获取路径的一个简单实现

反射方式获取properties文件的三种方式

1 反射方式获取properties文件最常用方法以及思考:
Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但我见到众多读取properties文件的代码中,都会这么干:
 

InputStream in = getClass().getResourceAsStream("资源Name");

2 获取路径的方式:

File fileB = new File( this .getClass().getResource( "" ).getPath());

System. out .println( "fileB path: " + fileB);

3 利用反射的方式获取路径:

InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "xx/xx/xx/xx.properties" );

InputStream ips2 = Enumeration . class .getResourceAsStream( "xx.properties" );

InputStream ips3 = Enumeration . class .getResourceAsStream( "xx/xx.properties" );

猜你喜欢

转载自blog.csdn.net/a913858/article/details/82769869
今日推荐