这篇博客记录平时一些可以重复使用的辅助程序。多了以后或许可以做成一个库。
PropertiesReader
使用
文件
D:\workspace\RyanTool\doc\test.properties
显示所有内容
1 2 3
| String filePath = "D:\\workspace\\RyanTool\\doc\\test.properties"; PropertiesReader propertiesReader = new PropertiesReader(); propertiesReader.printAll(filePath);
|
根据特定的key获取value:
1 2 3
| String filePath = "D:\\workspace\\RyanTool\\doc\\test.properties"; PropertiesReader propertiesReader = new PropertiesReader(); System.out.println(propertiesReader.getByKey("age", filePath));
|
PropertiesReader.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| package ryanluoxu.tool;
import java.io.File; import java.io.FileInputStream; import java.util.Enumeration; import java.util.Properties;
public class PropertiesReader { /** * Key must be unique. * @param key * @param filePath * @return value */ public String getByKey(String key, String filePath) { String value = null; Properties properties = new Properties(); try { File file = new File(filePath); FileInputStream fileInput = new FileInputStream(file); properties.load(fileInput); fileInput.close(); } catch (Exception e) { System.err.println(">>> Error when loading properties file.."); } Enumeration<Object> enuKeys = properties.keys(); while (enuKeys.hasMoreElements()) { String k = (String) enuKeys.nextElement(); if (k.equals(key)) { value = properties.getProperty(k); break; } } return value; } /** * print all values * @param filePath */ public void printAll(String filePath) { Properties properties = new Properties(); try { File file = new File(filePath); FileInputStream fileInput = new FileInputStream(file); properties.load(fileInput); fileInput.close(); } catch (Exception e) { System.err.println(">>> Error when loading properties file.."); } Enumeration<Object> enuKeys = properties.keys(); while (enuKeys.hasMoreElements()) { String k = (String) enuKeys.nextElement(); String value = properties.getProperty(k); System.out.println(k + ": " + value); } } }
|