1. 程式人生 > >通用工具類,獲取配置檔案資訊

通用工具類,獲取配置檔案資訊

創作不易,請勿抄襲,轉載請註明出處。如有疑問,請加微信 wx15151889890,謝謝。
[本文連結:]https://blog.csdn.net/wx740851326/article/details/83744404
之前已經寫過了這個文章,現在把整個類粘出來
文章也用markdown來寫了,希望更方便大家閱讀
如今的應用程式越來越講究可配置,任何可以改成配置檔案的地方最好都使用配置檔案,方便自己,方便他人。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

/**
 * define common handlers
 * 
 * @author dmvoishi
 * @since  20181024
 * @category getPropertiesFromHDFS getPropertiesFromLocal getProperty
 */
public class CommonUtils {

	// 讀取hdfs配置檔案
	public static Properties getPropertiesFromHDFS(String path) {
		Properties prop = new Properties();
		Configuration conf = new Configuration();
		FSDataInputStream hdfsInStream = null;
		// String path = "hdfs:///user/hdfs/redis.cfg";
		// String path = "c:\\hadoop\redis.cfg";
		try {
			FileSystem fs = FileSystem.get(URI.create(path), conf);
			hdfsInStream = fs.open(new Path(path));
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		InputStreamReader read = null;
		try {
			read = new InputStreamReader(hdfsInStream, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			prop.load(read);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return prop;
	}

	// 讀取本地配置檔案
	public static Properties getPropertiesFromLocal(String path) {
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			File f = new File(path);
			fis = new FileInputStream(f);
			prop.load(fis);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return prop;
	}

	public static Properties getProperty(String path, String pathType) {
		Properties properties = null;
		if (pathType == "local") {
			properties = CommonUtils.getPropertiesFromLocal(path);
		}
		if (pathType == "hdfs") {
			properties = CommonUtils.getPropertiesFromHDFS(path);
		}

		return properties;
	}
}