假设项目路径是E:\Workspaces\MyProgram\FilePath
1.使用System.getProperty("user.dir"),获得项目的根路径,返回String:E:\Workspaces\MyProgram\FilePath
2.使用File对象提供的获取绝对路径的方法获取根路径,new File("").getAbsolutePath(),返回String:E:\Workspaces\MyProgram\FilePath
3.可以使用File对象获取标准路径的方法来控制:
1)new File("..").getCanonicalPath(),返回String:E:\Workspaces\MyProgram
2)new File(".").getCanonicalPath(),返回String:E:\Workspaces\MyProgram\FilePath
4.使用class对象的getResource()方法获得bin目录,getClass().getResource(""),返回URL对象:file:/E:/Workspaces/MyProgram/FilePath/bin/
5. 使用ClassLoader对象的getResource()方法获得bin目录,getClass().getClassLoader().getResource(""),返回URL对象:file:/E: /Workspaces/MyProgram/FilePath/bin/
建议:
1.对于要获得的目录不在bin目录下的操作,可以使用1、2、3方式获得根目录,然后具体处理。
<