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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值