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

来源:互联网 发布:正方软件怎么样 编辑:程序博客网 时间:2024/06/05 14:48

// 获取绝对路径
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

 

原创粉丝点击