1. 程式人生 > >專案中的引數化配置

專案中的引數化配置

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

import com.retail.supmarket.http.controller.SweepCodePaymentController;

public class ReadFileUtil {

	/**
	 * 
	 * @Title: readFile 從properties檔案中讀取url的配置資訊
	 * @Description: TODO String
	 * @author Administrator
	 */
	public static String readFile(String proper) {
		Properties properties = new Properties();
		// 使用ClassLoader載入properties配置檔案生成對應的輸入流
		InputStream in = SweepCodePaymentController.class.getClassLoader().getResourceAsStream("url.properties");
		// 使用properties物件載入輸入流
		try {
			properties.load(in);
		} catch (IOException e) {
			System.out.println("請在配置中檢查url的配置是否正確" + e);
			e.printStackTrace();
		}
		// 獲取key對應的value值
		String getHttpProperty = properties.getProperty(proper);
		return getHttpProperty;
	}
}
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class ReadFileUtil {
	private static final String DEFAULT_ENCODING = "UTF-8";

	/**
	 * 
	 * @Title: readFile 從properties檔案中讀取url的配置資訊
	 * @Description: TODO String
	 * @author Administrator
	 */
	public static String readFile(String proper) {
		try {
			// 獲取檔案流(方法1或2均可)
			//InputStream inputStream = new BufferedInputStream(
					//new FileInputStream(new File("/src/main/resources/url.properties"))); // 方法1
			 InputStream inputStream =
			 Thread.currentThread().getContextClassLoader().getResourceAsStream("url.properties");
			// //方法2
			Properties prop = new Properties();

			prop.load(new InputStreamReader(inputStream, DEFAULT_ENCODING)); // 載入格式化後的流

			String driverClassName = prop.getProperty(proper);
			return driverClassName;

		} catch (FileNotFoundException e) {
			System.out.println("properties檔案路徑有誤!");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return proper;
	}
}

java讀取資源參考部落格:

https://www.cnblogs.com/shuimuzhushui/p/7247864.html

在jar檔案下面讀取:

https://www.cnblogs.com/TonyYPZhang/p/6298422.html

用類載入讀取配置檔案:

https://www.cnblogs.com/1540340840qls/p/6184109.html