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()时设定的路径 ;

扫描二维码关注公众号,回复: 7077325 查看本文章

例:当前的路径为 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();                    //得到的是.. 

 

猜你喜欢

转载自www.cnblogs.com/linkenpark/p/11397121.html