1. 程式人生 > >java讀取不到properties檔案所在路徑

java讀取不到properties檔案所在路徑

問題

  • 在java中讀取properties屬性,發現配置的讀取路徑找不到properties檔案。
InputStream in;
Properties pro = new Properties();
in = new FileInputStream(new File("src/config/data.properties"));
pro.load(in);
  • 此處路徑寫的不對,試過另一種方式,可以讀取到檔案並解析屬性,但是如果這段程式碼是在web工程的某個jar包內,則這種方式在tomcat下沒問題,但放在websphere上就獲取不到路徑了。
Test.class.getResource("/"
).getPath() + "/config/data.properties"

解決

  /**
    * 取得當前類所在的檔案
    * @param clazz
    * @return
    */
    public static File getClassFile(Class clazz){
       URL path = clazz.getResource(clazz.getName().substring(
               clazz.getName().lastIndexOf(".")+1)+".classs");
       if(path == null
){ String name = clazz.getName().replaceAll("[.]", "/"); path = clazz.getResource("/"+name+".class"); } return new File(path.getFile()); } /** * 得到當前類的路徑 * @param clazz * @return */ public static String getClassFilePath(Class clazz){ try
{ return java.net.URLDecoder.decode(getClassFile(clazz).getAbsolutePath(),"UTF-8"); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); return ""; } } /** * 取得當前類所在的ClassPath目錄,比如tomcat下的classes路徑 * @param clazz * @return */ public static File getClassPathFile(Class clazz){ File file = getClassFile(clazz); for(int i=0,count = clazz.getName().split("[.]").length; i<count; i++) file = file.getParentFile(); if(file.getName().toUpperCase().endsWith(".JAR!")){ file = file.getParentFile(); } return file; } /** * 取得當前類所在的ClassPath路徑 * @param clazz * @return */ public static String getClassPath(Class clazz){ try{ return java.net.URLDecoder.decode(getClassPathFile(clazz).getAbsolutePath(),"UTF-8"); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); return ""; } }

通過上面的方法呼叫就可以了

InputStream in;
Properties pro = new Properties();
String clspath = getClassPath(LoadMiddleTables.class);
in = new FileInputStream(new File(clspath+"/config/data.properties"));
pro.load(in);