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

     

  • 相关阅读:
    [LeetCode] 294. Flip Game II 翻转游戏之二
    [LeetCode] 293. Flip Game 翻转游戏
    [LeetCode] 266. Palindrome Permutation 回文全排列
    [LeetCode] 288. Unique Word Abbreviation 独特的单词缩写
    [LeetCode] Self Crossing 自交
    [LeetCode] 281. Zigzag Iterator 之字形迭代器
    [LeetCode] 251. Flatten 2D Vector 压平二维向量
    [LeetCode] 250. Count Univalue Subtrees 计数相同值子树的个数
    [LeetCode] 249. Group Shifted Strings 群组偏移字符串
    [LeetCode] 248. Strobogrammatic Number III 对称数之三
  • 原文地址:https://www.cnblogs.com/linkenpark/p/11397121.html
Copyright © 2020-2023  润新知