1.1 路径
在IO中,常用到路径的概念,有以下几种路径:
- c:\temp\file.txt
- .\file.txt
- c:\temp\MyApp\bin…\file.txt
第一类,属于路径,绝对路径,规范路径 (CanonicalPath)
第二类,属于路径,相对路径(Path)
第三类,属于路径,绝对路径 (AbsolutePath)
下面的示例代码清楚的展示了java中这三类路径的区别
/* -------这是一个相对路径的代码------- */
File file = new File("..\\..\\..\\Test.txt");
System.out.println("file.getAbsolutePath() -> " + file.getAbsolutePath());
System.out.println("file.getCanonicalPath() -> " + file.getCanonicalPath());
System.out.println("file.getPath() -> " + file.getPath());
/* -------输出------- */
file.getAbsolutePath() -> E:\commonWorkspace\IdeaPluginDevGuide\DevGuideVirtualFileSystem\..\..\..\Test.txt
file.getCanonicalPath() -> E:\Test.txt
file.getPath() -> ..\..\..\Test.txt
可以看到Path就是创建File时使用的相对目录。AbsolutePath是绝对路径,其中可能包含…/ or ./这类切换目录的相对目录,而CanonicalPath就是规范化后的绝对路径。leetcode有一题就是规范化路径的,71-简化路径,链接如下
https://leetcode-cn.com/problems/simplify-path/
1.2 File类
该类主要用来抽象文件系统,并对其进行操作,类似于Linux的ls命令。
为了代码可以在多种操作系统上创建文件对象,目录中的分隔符建议采用File.separator。
String fileName = "test.txt";
System.out.println("File.separator:" + File.separator);
File testFile = new File("D:" + File.separator + "filepath" + File.separator + "test" + File.separator + fileName);
File fileParent = testFile.getParentFile();//返回的是File类型,可以调用exsit()等方法
String fileParentPath = testFile.getParent();//返回的是String类型
System.out.println("fileParent:" + fileParent);
System.out.println("fileParentPath:" + fileParentPath);
if (!fileParent.exists()) {
fileParent.mkdirs();// 能创建多级目录
}
if (!testFile.exists()){
try {
testFile.createNewFile();//有路径才能创建文件
}catch (IOException e){
e.printStackTrace();
}
}
System.out.println(testFile);
String path = testFile.getPath();
String absolutePath = testFile.getAbsolutePath();//得到文件/文件夹的绝对路径
String getFileName = testFile.getName();//得到文件/文件夹的名字
System.out.println("path:"+path);
System.out.println("absolutePath:"+absolutePath);