获取资源文件*.properties的信息
user.properties
username = Peter password = 123456 age = 30 job = CTO
Test.java
package cn.itcast.demo.test; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class Test { public static void main(String[] args) { String filename = "G:\\Test\\Demo\\bin\\user.properties"; String username = getValueByKey(filename, "username"); String password = getValueByKey(filename, "password"); String job = getValueByKey(filename, "job"); Integer age = Integer.parseInt(getValueByKey(filename, "age")); System.out.println(username + "\n" + password + "\n" + job + "\n" + age); } public static String getValueByKey(String filename, String key) { Properties ps = new Properties(); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(filename)); ps.load(is); String value = ps.getProperty(key); return value; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (is != null) { try { is.close(); is = null; } catch (IOException e) { e.printStackTrace(); } } } } }
结果:
Peter
123456
CTO
30