java项目中加载资源文件

在java项目中加载资源文件有三种方式:

  1. 使用绝对路径加载
  2. 利用classpath路径加载资源文件。
  3. 利用调用资源文件类的字节码所在的路径加载资源文件。
public class LoadResoureces2 {
	public static void main(String[] args) throws IOException {
		 load1();
         load3();
		 load2();


	}
	// 从classpath根目录下加载资源文件
	public static void load1() throws IOException {
		InputStream inputStream =LoadResoureces2.class.getClassLoader().getResourceAsStream("db.properties");
		//InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
		Properties p = new Properties();
		p.load(inputStream);
		System.out.println(p);
		inputStream.close();
	}
	//从访问资源文件的类的字节码同级目录加载资源文件
	public static void load2() throws IOException {
		InputStream inputStream =LoadResoureces2.class.getResourceAsStream("dbio.properties");
		Properties p = new Properties();
		p.load(inputStream);
		System.out.println(p);
		inputStream.close();
	}

	//从资源的绝对路径来加载资源文件
	public static void load3() throws IOException {
		InputStream inputStream = new FileInputStream("E:/idea-workspace/LearnJavaByMike/resources/db1.properties");
		Properties p = new Properties();
		p.load(inputStream);
		System.out.println(p);
		inputStream.close();
	}
}

在项目中使用方式2来加载资源文件。

把资源文件放在项目resources 文件夹下,编译之后,资源文件就在classPath 路径下。

猜你喜欢

转载自blog.csdn.net/fanzhikangkang/article/details/107761822