• Java处理文件路径的类


    转帖说明:非常的好用,方便在进行Velocity和FreeMarker生成文件时候处理要生成文件的路径问题

    package util;

    import java.io.File;
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
     
    /** *//**
    * @author <a href="mailto:maryang@live.cn" mce_href="Maryangmailto:maryang@live.cn">Maryang</a>
    * @version $Revision: 1.0 $
    * 这个类提供了一些根据类的class文件位置来定位的方法。
    */
    public class PathUtil {
       
        /** *//**
         * 获取一个Class的绝对路径
         * @param clazz Class对象
         * @return Class的绝对路径
         */
        public static String getPathByClass(Class clazz){
            String path = null;
            try {
                URI uri = clazz.getResource("").toURI();
                File file = new File(uri);
                path = file.getCanonicalPath();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return path;
        }
       
        /** *//**
         * 获取一个文件相对于一个Class相对的绝对路径
         * @param clazz Class对象
         * @param relativePath Class对象的相对路径
         * @return 文件绝对路径
         */
        public static String getFilePathByClass(Class clazz,String relativePath){
            String filePath = null;
            String clazzPath = getPathByClass(clazz);
            StringBuffer sbPath = new StringBuffer(clazzPath);
            sbPath.append(File.separator);
            sbPath.append(relativePath);
            File file = new File(sbPath.toString());
            try {
                filePath = file.getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return filePath;
        }
        public static void main(String[] args) {
            try {
                System.out.println(getPathByClass(PathUtil.class));
               System.out.println(getFilePathByClass(PathUtil.class,"../../images/logo.gif"));
               System.out.println(getFilePathByClass(PathUtil.class,"../../../"));
              
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*

    E:/MyWorkspace/FreeMarkerTest/WebRoot/WEB-INF/classes/util
    E:/MyWorkspace/FreeMarkerTest/WebRoot/WEB-INF/images/logo.gif
    E:/MyWorkspace/FreeMarkerTest/WebRoot

    */

  • 相关阅读:
    管理索引表:深入研究B树索引重建,合并,删除(理论篇3)
    关于ASP.NET中Membership进行权限管理不足的解决办法
    将VS2005中的.CS文件在网页中显示的方法
    在页面中直接设计TreeView的节点而不使用Web.Sitemap文件在运行时出错
    (转)动态管理ASP.NET DataGrid数据列
    在页面中直接设计TreeView的节点而不使用Web.Sitemap文件在运行时出错
    将VS2005中的.CS文件在网页中显示的方法
    三天没有更新我的BLOG
    三天没有更新我的BLOG
    (转)动态管理ASP.NET DataGrid数据列
  • 原文地址:https://www.cnblogs.com/xqf222/p/3306782.html
Copyright © 2020-2023  润新知