zoukankan      html  css  js  c++  java
  • java获取当前路径的方法

    1、System.getProperty("user.dir") 函数获取当前路径

     1         // 获取当前路径方式1
     2         System.out.println(System.getProperty("user.dir"));
     3         String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "com" + File.separator + "java" + File.separator + "service" + "Data.java";
     4         System.out.println(filePath);
     5 
     6         // 获取当前路径方式2
     7         File f = new File(".");
     8         try {
     9             String filePath2 = f.getCanonicalPath() + File.separator + "src" + File.separator + "com" + File.separator + "java" + File.separator + "service" + "Data.java";
    10             System.out.println(filePath2);
    11         } catch (IOException e) {
    12             e.printStackTrace();
    13         }

    2、利用File类提供的方法获取文件路径

    getCanonicalPath( )

        得到相对路径;相对路径:“."就表示当前的文件夹,而”..“则表示当前文件夹的上一级文件夹 ;

    getAbsolutePath( )

        得到绝对路径;绝对路径: 则不管”.”、“..”,返回当前的路径加上你在new File()时设定的路径 ;

    getPath( )

        得到的只是你在new File()时设定的路径 ;

    例:当前的路径为 C:/test : 

        (1)File directory = new File("abc"); 
                directory.getCanonicalPath(); //得到的是C:/test/abc 
                directory.getAbsolutePath();    //得到的是C:/test/abc 

                direcotry.getPath();                    //得到的是abc 

        (2)File directory = new File("."); 
                directory.getCanonicalPath(); //得到的是C:/test 
                directory.getAbsolutePath();    //得到的是C:/test/. 

                direcotry.getPath();                    //得到的是. 

        (3)File directory = new File(".."); 
                directory.getCanonicalPath(); //得到的是C:/ 
                directory.getAbsolutePath();    //得到的是C:/test/.. 
                direcotry.getPath();                    //得到的是.. 

     

  • 相关阅读:
    CentOS7 1 安装 ansible
    CentOS7 prometheus +node_exporter+Grafana 配置篇(原创)
    CentOS7 prometheus +node_exporter+Grafana 安装篇
    Oracle 查询重复记录 只保留一条 (转载)
    MySQL 查询重复数据(转载)
    Mongodb 查询重复数据(转载)
    Python报错:pymongo.errors.CursorNotFound: Cursor not found
    百万级高并发MongoDB集群性能数十倍提升优化实践(上篇)
    OPPO百万级高并发mongodb集群性能数十倍提升优化实践(下篇) 转载
    Oracle 常见等待事件及处理方法
  • 原文地址:https://www.cnblogs.com/linkenpark/p/11397121.html
Copyright © 2011-2022 走看看