读取资源properties文件的写法

读取资源文件的方法有很多种,这种打jar是最方便的不会再报找不到文件了

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

public class ReadFile {
	
	public static void main(String[] args) throws Exception {
		//相对路径
//		String fileName = "../../file.txt";
		String fileName = "../../file.properties";
		ReadFile rf = new ReadFile();
		rf.readProp(fileName);
	}

	public void readText(String fileName) throws Exception {
		InputStream is = this.getClass().getResourceAsStream(fileName);
		byte[] b = new byte[1024];
		is.read(b);
		System.out.println(new String(b).trim());
	}
	
	public void readProp(String fileName) throws Exception {
		
		//读取文件
		InputStream is = this.getClass().getResourceAsStream(fileName);
		Properties prop = new Properties();
		prop.load(is);
		System.out.println("key: " + prop.getProperty("key"));
	}

}


猜你喜欢

转载自pluto418.iteye.com/blog/1189381