Java架构实践-如何解析Properties文件

1publicabstractclass ReadProperties { 2 3public ReadProperties() {} 4 5/** 6    * 回调函数,由调用者处理 7    * @param key 8    * @param value 9*/10publicabstractvoid dealKeyAndValue(String key, String value);1112/**13    * 根据包路径解析14    * @param packagePath15    * @throws IOException16*/17publicvoidread(String packagePath)throws IOException {18InputStream is =this.getClass().getResourceAsStream(packagePath);19        read(is);20    }2122/**23    * 根据文件的绝对路径解析24    * @param absolutePath25    * @throws IOException26*/27publicvoidreadFile(String absolutePath)throws IOException {28read(new File(absolutePath));29    }3031/**32    * 根据{@link File}解析33    * @param file34    * @throws IOException35*/36publicvoidread(File file)throws IOException {37read(new FileInputStream(file));38    }3940/**41    * 根据{@link InputStream}解析42    * @param is43    * @throws IOException44*/45publicvoidread(InputStream is)throws IOException {46Properties properties =new Properties();47try {48// Properties文件会出现乱码问题,以UTF-8的方式打开49properties.load(newInputStreamReader(is, "UTF-8"));50Enumeration keys = properties.keys();5152while (keys.hasMoreElements()) {53String key = (String) keys.nextElement();54String value = properties.getProperty(key);55                properties.get(key);5657                dealKeyAndValue(key, value);58            }59}finally {60            is.close();61        }62    }6364}


使用:

在src下新建一个test.properties文件如下:

Java架构实践-如何解析Properties文件_第1张图片


执行解析:

1publicclass Test { 2 3publicstaticvoidmain(String[] args)throws Exception { 4new ReadProperties() { 5            @Override 6publicvoid dealKeyAndValue(String key, String value) { 7System.out.println(key + " = " + value); 8            } 9}.read("/test.properties");;10    }1112}


结果如下:

Java架构实践-如何解析Properties文件_第2张图片


需要获取海量最新BATJ视频资料加群:345353515 备注()

你可能感兴趣的:(Java架构实践-如何解析Properties文件)