zoukankan      html  css  js  c++  java
  • 获取当前应用的系统路径工具类和java的System.getProperty()方法介绍

      java的System.getProperty()方法可以获取的值,如下:

      对于Java程序,无论是未打包的还是打包的JAR或WAR文件,有时候都需要获取它运行所在目录信息,如何做到这一点呢?  

     1 /**
     2  * 得到当前应用的系统路径
     3  */
     4 public class SystemPath {
     5     
     6     /*replace和replaceAll是JAVA中常用的替换字符的方法,它们的区别是:
     7         1)replace的参数是char和CharSequence,即可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列的意思,说白了也就是字符串);
     8         2)replaceAll的参数是regex,即基于规则表达式的替换,比如,可以通过replaceAll("\d", "*")把一个字符串所有的数字字符都换成星号;
     9     */
    10 
    11     /**
    12     *    得到当前应用的系统路径
    13      */
    14     public static String getSysPath() {
    15         //从classpath根开始查找
    16         String path = Thread.currentThread().getContextClassLoader()
    17                 .getResource("").toString();
    18         String temp = path.replaceFirst("file:/", "").replaceFirst(
    19                 "WEB-INF/classes/", "");
    20         //文件分隔符(在 UNIX 系统中是“/”)
    21         String separator = System.getProperty("file.separator");
    22         String resultPath = temp.replaceAll("/", separator + separator);
    23         return resultPath;
    24     }
    25 
    26     /**
    27     *    得到当前应用生成class文件的系统路径
    28      */
    29     public static String getClassPath() {
    30         String path = Thread.currentThread().getContextClassLoader()
    31                 .getResource("").toString();
    32         String temp = path.replaceFirst("file:/", "");
    33         String separator = System.getProperty("file.separator");
    34         String resultPath = temp.replaceAll("/", separator + separator);
    35         return resultPath;
    36     }
    37 
    38     /**
    39     *    默认的临时文件路径
    40      */
    41     public static String getSystempPath() {
    42         return System.getProperty("java.io.tmpdir");
    43     }
    44 
    45     /**
    46     *    文件分隔符(在 UNIX 系统中是“/”)
    47      */
    48     public static String getSeparator() {
    49         return System.getProperty("file.separator");
    50     }
    51 
    52     /**
    53     *    控制台打印显示
    54      */
    55     public static void main(String[] args) {
    56         System.out.println(getSysPath());
    57         System.out.println(System.getProperty("java.io.tmpdir"));
    58         System.out.println(getSeparator());
    59         System.out.println(getClassPath());
    60     }
    61 }
    1   文件终结符是 EOF, end of file
    2   行分隔符在windows 下是 ,在Linux下面是 , 在Mac下是
    3   路径分隔符在windows下是 ,在LInux下是 /

    转载请注明出处!

    http://www.cnblogs.com/libingbin/

    感谢您的阅读。如果文章对您有用,那么请轻轻点个赞,以资鼓励。

  • 相关阅读:
    构建之法东北师大站分数构成
    alpha发布排序结果
    展示一个响应式布局吧,没有效果图自己敲敲看吧@@@@
    vc++和LINGO编程
    [opencv] 极线校正
    [python] 小demo
    [python] socket模块(TCP/IP网络编程)
    树莓派学习【二】:(SSH+VNC)树莓派一根网线连电脑,不要显示屏
    树莓派学习【一】:树莓派的SSH连接
    css+div基本知识;
  • 原文地址:https://www.cnblogs.com/libingbin/p/6030710.html
Copyright © 2011-2022 走看看