java几种读取配置文件的情况

1、传统java项目,读取resource下的配置文件

  1.1、通过当前执行线程获取类加载器找到配置文件

        Properties properties = new Properties();
		InputStream is = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("GeoServerProperties.properties");
		try {
			properties.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}

		String serverURL = (String) properties.getProperty("serverURL", "");

1.2、直接通过类加载器获取路径

           

//本地运行
			String fileUrl = this.getClass().getClassLoader().getResource("espjsonData.json").toString();
			File file = new File(fileUrl.substring(5, fileUrl.length()));
			InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
			BufferedReader rd = new BufferedReader(reader);
//打包运行
		 InputStream ips = this.getClass().getResourceAsStream("/resources/espjsonData.json");
			 BufferedReader rd = new BufferedReader(new InputStreamReader(ips));

2、web项目,读取webapp下的配置文件

   

String path= request.getServletContext().getRealPath("/js/china_province_citys.json");
File file = new File(cityJsonPath);
	if (file.exists()) {
		try {
				BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
            } catch (Exception e) {
				e.printStackTrace();
			}
	}

 

你可能感兴趣的:(java)