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();                    //得到的是.. 

     

  • 相关阅读:
    efwplus框架
    注册区域
    社招面试记录与总结
    验证码 Captcha 之大插件
    发生内存泄漏?
    Flume+LOG4J+Kafka
    协议如何保证可靠传输
    oracle之spool详细使用总结(转)
    SSH协议详解(转)
    oracle nologging用法(转)
  • 原文地址:https://www.cnblogs.com/linkenpark/p/11397121.html
Copyright © 2011-2022 走看看