当前位置:科普知识站>IT科技>

java获得当前路径

IT科技 阅读(2.47W)

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

很多朋友都想知道java如何获得当前路径?下面就一起来了解一下吧~

1、利用System.getProperty()函数获取当前路径: 

System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径

java获得当前路径

2、使用File提供的函数获取当前路径: 

File directory = new File("");//设定为当前文件夹 try{     System.out.println(directory.getCanonicalPath());//获取标准的路径     System.out.println(directory.getAbsolutePath());//获取绝对路径 }catch(Exceptin e){} File.getCanonicalPath()和File.getAbsolutePath()大约只是对于new File(".")和new File("..")两种路径有所区别。 # 对于getCanonicalPath()函数,“."就表示当前的文件夹,而”..“则表示当前文件夹的上一级文件夹 # 对于getAbsolutePath()函数,则不管”.”、“..”,返回当前的路径加上你在new File()时设定的路径 # 至于getPath()函数,得到的只是你在new File()时设定的路径
比如当前的路径为 C:est :File directory = new File("abc");directory.getCanonicalPath(); //得到的是C:estabcdirectory.getAbsolutePath();    //得到的是C:estabcdirecotry.getPath();                    //得到的是abcFile directory = new File(".");directory.getCanonicalPath(); //得到的是C:estdirectory.getAbsolutePath();    //得到的是C:est.direcotry.getPath();                    //得到的是.File directory = new File("..");directory.getCanonicalPath(); //得到的是C:directory.getAbsolutePath();    //得到的是C:est..direcotry.getPath();                    //得到的是..