was 图片路径与存储 与tomcte不同

本文提供了一种方法来获取Java应用程序中当前类的路径及其所在ClassPath目录的方法。通过提供的代码片段,可以准确地定位到类文件的位置,并进一步获取其所在的根目录路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



    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 "";
        }
    }

下附我写的代码调用类


String classPath=getClassPath(this.getClass());
  //System.out.println(classPath);
  String rooPath = classPath.replaceAll("WEB-INF/classes/","");
  int j=rooPath.indexOf("WEB-INF");
  String rootPath=rooPath.substring(0,j);
  System.out.println(""+rootPath);
  String filePath = "";
  if("0".equals(vatType)){
   filePath = rootPath+"/template/bill/zzszy_invoice.png";
  }else{
   filePath = rootPath+"/template/bill/zzspy_invoice.png";
  }
  System.out.println("模板路径"+filePath);

fileName = fileName+System.currentTimeMillis() + ".png";
   String nF = rootPath+"/template/bill/outBill/" + fileName;
   System.err.println("输出路径"+nF);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值