Java.io包学习-获取文件的父目录

// 获取绝对路径
File file = new File("Ex1.java");
String parentPath = file.getParent(); // null
File parentDir = file.getParentFile(); // null

// 获取相对路径
file = new File("D:\\almanac\\Ex1.java");
parentPath = file.getParent(); // D:\almanac
parentDir = file.getParentFile(); // D:\almanac

parentPath = parentDir.getParent(); // D:\
parentDir = parentDir.getParentFile(); // D:\

parentPath = parentDir.getParent(); // null
parentDir = parentDir.getParentFile(); // null

 

 

 

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.zhutiai.com 也代表了一个URL绝对

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

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

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

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

(URI): Generic Syntax

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值