java配置文件路徑

java配置文件路徑寫法

java程序中經常使用配置文件,將程序打成jar包後,配置文件的路徑該如何設置,放於jar包內和外部時,代碼如何寫,在此做個記錄。

測試代碼

		System.out.println(123);

		System.out.println("user.dir:" + System.getProperty("user.dir"));
		System.out.println("user.home:" + System.getProperty("user.home"));
		
		//InputStream in = MainApp.class.getClassLoader().getResourceAsStream("config/config.ini");
		String protectionDomain = MainApp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		System.out.println("protectionDomain:" + protectionDomain);
		
		String path = System.getProperty("java.class.path");
		System.out.println("java.class.path:" + path);
		
		int firstIndex = path.lastIndexOf(System.getProperty("path.separator"))+1 ;
		int lastIndex = path.lastIndexOf(File.separator) +1; 
		path = path.substring(firstIndex, lastIndex); 
		System.out.println("path:" + path);
				
		System.out.println(321);

eclipse執行結果

![eclipse執行結果](https://img-blog.csdnimg.cn/2在這裏插入圖片描述

jar包不同路徑下執行結果

jar包不同路徑下執行結果

由此可見,使用user.dir設置配置文件路徑並不是一個很好的解決辦法,更好的應當選用protectionDomain,在程序和jar外部都可以方便使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章