通用工具类,获取配置文件信息

版权声明:创作不易,请勿抄袭,转载请注明出处。如有疑问,请加微信 wx15151889890,谢谢。 https://blog.csdn.net/wx740851326/article/details/83744404

创作不易,请勿抄袭,转载请注明出处。如有疑问,请加微信 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;
	}
}

猜你喜欢

转载自blog.csdn.net/wx740851326/article/details/83744404
今日推荐