Java代码获取classpath路径方法和资源文件的读取方法

classpath 是什么?简单从字面分析看 class path,即类路径,其实就是这个意思,Java程序工作时靠的是各种Java 类来进行工作,那这些工作类存放在哪里呢?这是个重要问题,一个Java工程项目,必须有个地方存放这些工作的Java类,这些类通常是工程的机密,所以就有个约定工程项目必须有个存放这些工作类的地方,于是从实际意义上考虑,自然而然的就有个 classpath 这个名称了,这个一般仅存放本工程项目开发的Java类和项目的一些配置文件,如 XML 和 properties 文件等,


1,那Java代码该如何获取 classpath 路径呢?

本例子以读取 classpath 下的 config.properties 文件,并读取其中的内容为例,综合介绍 classpath 的路径获取方法和读取配置 properties 文件中某个键的值的方法;

	static {
		String uploadFileDir = "";
		Properties prop = new Properties();
		try {
			String configFile = "config.properties";
			//以URL形式获取工程的资源文件 classpath 路径, 得到以file:/为开头的URL
			//例如返回: file:/D:/workspace/myproject01/WEB-INF/classes/ 
			URL classPath = Thread.currentThread().getContextClassLoader().getResource("");
			String proFilePath = classPath.toString();
			
			//移除开通的file:/六个字符
			proFilePath = proFilePath.substring(6); 
			
			//如果为window系统下,则把路径中的路径分隔符替换为window系统的文件路径分隔符
			proFilePath = proFilePath.replace("/", java.io.File.separator);
			
			//兼容处理最后一个字符是否为 window系统的文件路径分隔符,同时建立 properties 文件路径
			//例如返回: D:\workspace\myproject01\WEB-INF\classes\config.properties
			if(!proFilePath.endsWith(java.io.File.separator)){
				proFilePath = proFilePath + java.io.File.separator + configFile;
			} else {
				proFilePath = proFilePath + configFile;
			}
			
			//以文件流形式读取指定路径的配置文件 config.properties 
			FileInputStream ins = new FileInputStream(proFilePath);
			
			//以properties对象形式读取文件流
			prop.load(ins);
			
			//从properties中读取各个键(此以website.uploadfiledir为例)的值,付给适当变量
			uploadFileDir = prop.getProperty("website.uploadfiledir");
			
			//...其它操作...
			
		} catch (Exception e) {
			uploadFileDir = "";			
		}
		prop = null;
	}


2,Java把键值对写入 propties 到文件中的操作

try{
	Properties prop = new Properties();
	//随机生成键值以测试
	String tempSn=String.valueOf(Math.round((Math.random()*1000)));
	prop.setProperty("err.key" + tempSn, tempSn);
	
	String outFile = "d:\\bb.properties";
	//true追加,false=覆盖
	FileOutputStream fos = new FileOutputStream(outFile,true);
	
	//这里会把prop里面所有内容,(根据参数设置)追加或覆盖方式存储到输出的propties文件中
	prop.store(fos, "this is comment,add one key value,新增加一个键值对,这里是注释");
	
	fos.close(); //关闭输出流,释放资源
	
	//显示propties文件中内容
	FileInputStream fis = new FileInputStream(outFile);
	Properties prop2 = new Properties();
	prop2.load(fis);
	Iterator<String> it = prop2.stringPropertyNames().iterator();
	String key = "";
	while (it.hasNext()) {
		key = (String) it.next();
		System.out.println(key + "=" + prop2.getProperty(key));			
	}
	fis.close();
} catch (Exception e) {
	System.out.println(e.toString());
}

简单吧,就此即可读取 classpath 的配置properties 文件,再得到各个键值,再进行其它的系统后续操作。

可能有些遗漏,欢迎你拍砖讨论...



扫描二维码关注公众号,回复: 914194 查看本文章

猜你喜欢

转载自blog.csdn.net/shenzhennba/article/details/52420122