package readProperties; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class ReadMethod { public String useIO(String name){ /* * 使用IO讀取,注意文件位置不同時的路徑問題 */ /* * properties文件的管理類 */ Properties pro = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream("user.properties"); //fis = new FileInputStream("src/student.properties"); //fis = new FileInputStream("src/readProperties/emp.properties"); } catch (FileNotFoundException e) { e.printStackTrace(); } try { /* * 把文件加載到內存中(程序中) */ pro.load(fis); } catch (IOException e) { e.printStackTrace(); } String value = pro.getProperty(name); try { fis.close(); } catch (IOException e) { e.printStackTrace(); } return value; } public String useClassLoader(String name){ /* * 使用類加載器來加載,文件需要在src目錄下才可以加載, * 所以如果讀取user.properties會出現NullPointer,只可讀 */ //java.io.InputStream is = ReadMethod.class.getClassLoader().getResourceAsStream("readProperties/emp.properties"); java.io.InputStream is = ReadMethod.class.getClassLoader().getResourceAsStream("student.properties"); Properties pro = null; try { pro = new Properties(); pro.load(is); } catch (IOException e) { e.printStackTrace(); } String value = pro.getProperty(name); try { is.close(); } catch (IOException e) { e.printStackTrace(); } return value; } public String useClass(String name){ /* * 使用Class這個類的getResourceAsStream()加載, * 程序從當前類所在的包找,如果存在子包,需要加上 * 包名.當前類所在包外的資源無法 * 加載(無法加載student.properties和user.properties) */ java.io.InputStream is = ReadMethod.class.getResourceAsStream("emp.properties"); Properties pro = new Properties(); try { pro = new Properties(); pro.load(is); } catch (IOException e) { e.printStackTrace(); } String value = pro.getProperty(name); try { is.close(); } catch (IOException e) { e.printStackTrace(); } return value; } public static void main(String[] args) { ReadMethod rm = new ReadMethod(); //System.out.print(rm.useIO("jack")); //System.out.print(rm.useClassLoader("tom")); System.out.print(rm.useClass("mike")); } } 注意:初始化IO流會佔用系統資源,所以用完後需要關閉所有流,否則會浪費系統資源 說明:user.properties位於工程包下與src平級,內容jack=123456;student.properties位於src下,內容tom=math;emp.properties位於src/readProperties,內容mike=IT。