import Java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Iterator; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author zcb */ public class Test { public static void main(String args[]) { Test test = new Test(); InputStream in = null; Properties props = new Properties(); //第一种方法,取得src下的属性文件,成功 in = test.getClass().getResourceAsStream("/mypropertiestest.properties"); //第二种方法,取得src下的属性文件,相对第一种少了个“/”,注意:error,不行,此时取得的路径是到classes文件夹 // System.out.println("path:"+test.getClass().getResource("mypropertiestest.properties").getPath()); // in = test.getClass().getResourceAsStream("mypropertiestest.properties"); //第三种种方法,通过绝对路径,取得src下的属性文件,成功,但对apusic服务器不大理想,属性文件要拷贝到项目外面 // String filepath = test.getClass().getResource("/").getPath() + java.io.File.separator + "mypropertiestest.properties"; // try { //// filepath = filepath.substring(1).replaceAll("%20", " ");//or filepath = filepath.replaceAll("%20", " "); // filepath = URLDecoder.decode(filepath, "UTF-8"); // } catch (UnsupportedEncodingException ex) { // Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); // } // try { // in = new FileInputStream(new File(filepath)); // } catch (FileNotFoundException ex) { // Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); // } try { props.load(in); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex); } } } //输出属性文件中的信息 Set set = props.keySet(); Iterator it = set.iterator(); System.out.println("Begin ..."); while (it.hasNext()) { String key = (String) it.next(); System.out.println(key + "=" + props.getProperty(key)); } System.out.println("End"); } }
在Windows下测试通过,Linux没测试,需要进一步研究。