JDK工具类_____properties文件各种操作

来源:互联网 发布:宠物翻译器软件 编辑:程序博客网 时间:2024/06/09 18:16
package com.demo.test;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.Iterator;import java.util.Properties;import java.util.Map.Entry;/** * @author God * java属性文件的操作 */public class Test {public static void main(String[] args) throws Exception {//读取jvm配置参数systenGet();//filestream读取属性文件filestreamGet();//采用jvmclassload加载配置classloaderGet();//classload 加载中文乱码问题classLoadUTFGet();//初始化加载到内存中 直接从内存中读取参数loadTOMemory() ;}/** * system读取propertise文件 */public static void systenGet(){Properties properties=System.getProperties();System.out.println(properties.getProperty("user.dir"));}/** * 属相文件信息 */public static void filestreamGet() {Properties p = new Properties();try {FileInputStream fileInputStream = new FileInputStream("src/jdbc.properties");p.load(fileInputStream);System.out.println(p.getProperty("username"));fileInputStream.close();} catch (Exception e) {e.printStackTrace();}}/** * classloader读取属性文件 */public static void classloaderGet(){ClassLoader load=ClassLoader.getSystemClassLoader();Properties p=new Properties();try {p.load(load.getResourceAsStream("jdbc.properties"));} catch (IOException e) {e.printStackTrace();}System.out.println(p.getProperty("username"));}/** * 读取properties 文件乱码解决方法 */public static void classLoadUTFGet(){ClassLoader load=ClassLoader.getSystemClassLoader();Properties p=new Properties();try {p.load(new InputStreamReader(load.getResourceAsStream("jdbc.properties"), "UTF-8"));} catch (IOException e) {e.printStackTrace();}System.out.println("解决中文乱码的方法___:"+p.getProperty("sex"));}public static void loadTOMemory() throws Exception{// 初始化工工程时加载配置文件Properties properties = new Properties();FileInputStream fileInputStream = null;fileInputStream = new FileInputStream("src/jdbc.properties");//propereties工具类从流中加载文件properties.load(fileInputStream);if (null != fileInputStream) {//一定要关闭流 不关闭流会照成好多问题fileInputStream.close();}Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();while (iterator.hasNext()) {Entry<Object, Object> e = iterator.next();System.setProperty(e.getKey().toString(), e.getValue().toString());}System.out.println("从内存中读取配置_______:"+System.getProperty("username"));}}

//工程结构


//属性文件


//运行结果


1 0