posts - 2,  comments - 0,  trackbacks - 0

java中获得当前文件路径多种方法


public  String getClassPath(){
        String path="";
 try {
path=new File(getClass().getClassLoader().getResource("").toURI()).getPath();
     }catch (URISyntaxException ex) {}
        return path;
}

取程序运行时的目录路径。即程序在那里双击或BAT文件所在的路径

System.getProperties("user.dir");

第一种: 

File f = new File(this.getClass().getResource("/").getPath()); 
System.out.println(f); 

结果: 

C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebin 

获取当前类的所在工程路径; 
如果不加“/” 

File f = new File(this.getClass().getResource("").getPath()); 
System.out.println(f); 

结果: 

C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebincomtest 

获取当前类的绝对路径;

第二种: 

File directory = new File("");//参数为空 
String courseFile = directory.getCanonicalPath() ; 

System.out.println(courseFile); 
结果: 

C:Documents and SettingsAdministratorworkspaceprojectName 

获取当前类的所在工程路径;

第三种: 

URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt"); 
System.out.println(xmlpath); 

结果: 
file:/C:/Documents%20and%

20Settings/Administrator/workspace/projectName/bin/selected.txt 

获取当前工程src目录下selected.txt文件的路径

第四种: 

System.out.println(System.getProperty("user.dir")); 

结果: 

C:Documents and SettingsAdministratorworkspaceprojectName 

获取当前工程路径

第五种: 

System.out.println( System.getProperty("java.class.path")); 

结果: 

C:Documents and SettingsAdministratorworkspaceprojectNamebin 

获取当前工程路径

绝对路径和相对路径: 
绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如:C:xyz

est.txt 代表了test.txt文件的绝对路径。http://www.111cn.net 也代表了一个URL绝对

路径。相对路径:相对与某个基准目录的路径。包含Web的相对路径(HTML中的相对目录)

,例如:在Servlet中,"/"代表Web应用的跟目录。和物理路径的相对表示。例如:"./" 代

表当前目录,"../"代表上级目录。这种类似的表示,也是属于相对路径。另外关于URI,

URL,URN等内容,请参考RFC相关文档标准。RFC 2396: Uniform Resource Identifiers

(URI): Generic Syntax
[以上摘自:http://www.111cn.net/jsp/Java/39141.htm]

posted on 2014-04-19 15:32 黑客的蜗牛 阅读(10836) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
<2014年4月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

这个家伙很懒,神马都没有写

常用链接

留言簿

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜