如何获得当前Java文件的路径

如题,比如说,我正在eclipse中编写一个Java文件,然后呢,我想找到这个Java文件的所在的目录,注意,不是classpath的路径,因为class.getresource().getpath()等类似的语句目录是bin,而不会是Java文件所在的路径。要怎么弄呢。还请各位支招。

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

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

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


Java基础知识教程:

温馨提示:内容为网友见解,仅供参考
第1个回答  2015-09-09
绝对路径:
File f = new File(this.getClass().getResource("/").getPath()); 
System.out.println(f);

第2个回答  推荐于2017-10-06
public class Test {
public static void main(String[] args) {
String path = "Test.java";
File file = new File(path);
System.out.println(file.getAbsoluteFile());
}
}

-----
运行结果:
D:\workspaces\studyStruts2\Test.java
不加任何路径,就是指当前路径
望采纳追问

谢谢,这个Test.java的路径上层路径呢?就是D:\workspaces\studyStruts2
怎么得到呢。

追答

不好意思,昨天理解错了,看我今天写的这个,希望对你有帮助,忘采纳
public static void main(String[] args) throws IOException { File file1 = new File(""); String projectPath = file1.getAbsolutePath();//获取项目目录 System.out.println(file1.getAbsolutePath()); //D:\workspaces\studyStruts2 File file = new File(Test.class.getName()); String javapath = file.getPath(); System.out.println(javapath); //org.xmh.demo.Test //所以获取java文件的本地绝对路径为: String path = projectPath+"\\src\\"+javapath.replace(".", "\\")+".java"; System.out.println(path); //D:\workspaces\studyStruts2\src\org\xmh\demo\Test.java //这就是java文件的本地绝对路径啦 }

本回答被提问者和网友采纳
相似回答