File IO(NIO.2):路径类 和 路径操作
路径类
Java SE 7版本中引入的Path类是java.nio.file包的主要入口点之一。如果您的应用程序使用文件I / O,您将需要了解此类的强大功能。
版本注意:如果您有使用java.io.File的JDK7之前的代码,则仍然可以使用File.toPath方法来利用Path类功能。有关详细信息,请参阅传统文件I / O代码。
顾名思义,Path类是文件系统中路径的编程表示形式。路径对象包含用于构建路径的文件名和目录列表,用于检查,定位和操作文件。
路径实例反映了底层平台。在Solaris OS中,路径使用Solaris语法(/ home / joe / foo),而在Microsoft Windows中,路径使用Windows语法(C:\ home \ joe \ foo)。路径与系统无关。您不能将Solaris与Solaris文件系统进行比较,并期望它与Windows文件系统中的路径相匹配,即使目录结构相同,并且两个实例都找到相同的相对文件。
与Path相对应的文件或目录可能不存在。您可以创建一个Path实例并以各种方式进行操作:您可以附加它,提取它,并将其与其他路径进行比较。在适当的时候,您可以使用Files类中的方法检查与Path对应的文件的存在,创建文件,打开它,删除它,更改其权限等。
下一页将详细介绍Path类。
路径操作
简介
创建一个路径
Path p1 = Paths.get("/tmp/foo");
Path p2 = Paths.get(args[0]);
Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
Paths.get方法是以下代码的缩写:
Path p4 = FileSystems.getDefault().getPath("/users/sally");
以下示例创建/u/joe/logs/foo.log,假设您的主目录是/ u / joe,或者C:\ joe \ logs \ foo.log(如果您在Windows上)。
Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
检索路径信息
// None of these methods requires that the file corresponding
// to the Path exists.
// Microsoft Windows syntax
Path path = Paths.get("C:\\home\\joe\\foo"); // Solaris syntax
Path path = Paths.get("/home/joe/foo"); System.out.format("toString: %s%n", path.toString());
System.out.format("getFileName: %s%n", path.getFileName());
System.out.format("getName(0): %s%n", path.getName(0));
System.out.format("getNameCount: %d%n", path.getNameCount());
System.out.format("subpath(0,2): %s%n", path.subpath(0,2));
System.out.format("getParent: %s%n", path.getParent());
System.out.format("getRoot: %s%n", path.getRoot());
以下是Windows和Solaris操作系统的输出:
上一个示例显示绝对路径的输出。在以下示例中,指定了相对路径:
// Solaris syntax
Path path = Paths.get("sally/bar");
or
// Microsoft Windows syntax
Path path = Paths.get("sally\\bar");
以下是Windows和Solaris OS的输出:
从路径中删除冗余数据
/home/sally/../joe/foo
转换路径
Path p1 = Paths.get("/home/logfile");
// Result is file:///home/logfile
System.out.format("%s%n", p1.toUri());
toAbsolutePath方法将路径转换为绝对路径。如果传入路径已经是绝对路径,则返回相同的路径对象。在处理用户输入的文件名时,toAbsolutePath方法非常有用。例如:
public class FileTest {
public static void main(String[] args) { if (args.length < 1) {
System.out.println("usage: FileTest file");
System.exit(-1);
} // Converts the input string to a Path object.
Path inputPath = Paths.get(args[0]); // Converts the input Path
// to an absolute path.
// Generally, this means prepending
// the current working
// directory. If this example
// were called like this:
// java FileTest foo
// the getRoot and getParent methods
// would return null
// on the original "inputPath"
// instance. Invoking getRoot and
// getParent on the "fullPath"
// instance returns expected values.
Path fullPath = inputPath.toAbsolutePath();
}
}
toAbsolutePath方法转换用户输入并返回一个在查询时返回有用值的路径。该文件不需要存在,以使此方法正常工作。
try {
Path fp = path.toRealPath();
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
// Logic for case when file doesn't exist.
} catch (IOException x) {
System.err.format("%s%n", x);
// Logic for other sort of file error.
}
联合两个路径
// Solaris
Path p1 = Paths.get("/home/joe/foo");
// Result is /home/joe/foo/bar
System.out.format("%s%n", p1.resolve("bar"));
或者
// Microsoft Windows
Path p1 = Paths.get("C:\\home\\joe\\foo");
// Result is C:\home\joe\foo\bar
System.out.format("%s%n", p1.resolve("bar"));
将绝对路径传递给resolve方法返回传入路径:
// Result is /home/joe
Paths.get("foo").resolve("/home/joe");
在两个路径之间创建一个新的路径
Path p1 = Paths.get("joe");
Path p2 = Paths.get("sally");
对于其他信息而言,假设 Joe 和 Sally是兄妹,这意味着这个节点在树结构中有着同等的等级。 要想通过 Joe找到Sally,你可能需要首先找到这个父节点,然后找到Sally。
// Result is ../sally
Path p1_to_p2 = p1.relativize(p2);
// Result is ../joe
Path p2_to_p1 = p2.relativize(p1);
再看一个略微复杂的例子:
Path p1 = Paths.get("home");
Path p3 = Paths.get("home/sally/bar");
// Result is sally/bar
Path p1_to_p3 = p1.relativize(p3);
// Result is ../..
Path p3_to_p1 = p3.relativize(p1);
在这个例子中,两个路径共享了一个节点:home。 从home找到了bar,首先需要找到一个等级(home),然后再查找下一个等级找到Sally,最后再找到bar。从bar要找到home,需要向上查找两个等级。
这个Copy 的递归例子,使用了relativize 和 resolve 方法。
比较两个路径
Path path = ...;
Path otherPath = ...;
Path beginning = Paths.get("/home");
Path ending = Paths.get("foo"); if (path.equals(otherPath)) {
// equality logic here
} else if (path.startsWith(beginning)) {
// path begins with "/home"
} else if (path.endsWith(ending)) {
// path ends with "foo"
}
Path类实现了Iterable接口,iterator方法返回一个对象,而这个对象让你可以遍历路径中的所有节点名称。第一个被返回的节点,是离目录树最近的根节点。下面的代码简单的遍历了一个路径,并打印每一个节点的名称:
Path path = ...;
for (Path name: path) {
System.out.println(name);
}
Path类同样实现了comparable接口,你可以比较路径对象通过comparaTo方法,这个方法对于排序也同样有用。
File IO(NIO.2):路径类 和 路径操作的更多相关文章
- 【C# IO 操作】 Path 路径类 |Directory类 |DirectoryInfo 类|DriveInfo类|File类|FileInfo类|FileStream类
Directory类 Directory类 是一个静态类,常用的地方为创建目录和目录管理. 一下来看看它提供的操作. 1.CreateDirectory 根据指定路径创建目录.有重载,允许一次过创建多 ...
- 绝对路径和相对路径和File类的构造方法
路径: 绝对路径:是一个完整的路径 以盼复(C:,D:)开始的路径 c:\a.txt C:\User\itcast\IdeaProjects\shungyuan\123.txt D:\demo\b.t ...
- C# 一些知识点总结(二)_路径类,编码类,文件类...
Path 类:路径类path.GetFileName("文件路径")//获取完整文件名,包括文件名和文件拓展名Path.GetFileNameWithoutExtension(&q ...
- paip兼容windows与linux的java类根目录路径的方法
paip兼容windows与linux的java类根目录路径的方法 1.只有 pathx.class.getResource("")或者pathx.class.getResourc ...
- Java笔记(二十七)……IO流中 File文件对象与Properties类
File类 用来将文件或目录封装成对象 方便对文件或目录信息进行处理 File对象可以作为参数传递给流进行操作 File类常用方法 创建 booleancreateNewFile():创建新文件,如果 ...
- java相对路径、绝对路径及类路径
import java.io.File; import java.net.URL; /** * java相对路径.绝对路径及类路径的测试 */ public class Test { /** * 测试 ...
- File构建实例的路径:绝对路径和相对路径
public static void main(String[] args) throws Exception { File file = new File("bin/dyan.txt&qu ...
- Java IO流中 File文件对象与Properties类(四)
File类 用来将文件或目录封装成对象 方便对文件或目录信息进行处理 File对象可以作为参数传递给流进行操作 File类常用方法 创建 booleancreateNewFile():创建新文件,如果 ...
- path类和directory类对文件的路径或目录进行操作
Path: 对文件或目录的路径进行操作(很方便)[只是对字符串的操作] 1.目录和文件操作的命名控件System.IO 2.string Path.ChangeExtension(string ...
随机推荐
- IOS NSBundle使用(访问文件夹)
NSBundle的相关信息 1.一个NSBundle代表一个文件夹,利用NSBundle能访问对应的文件夹 2.利用mainBundle就可以访问软件资源包中的任何资源 3.模拟器应用程序的安装路径: ...
- 棋盘V(最小费用最大流)
棋盘V 时间限制: 1 Sec 内存限制: 128 MB提交: 380 解决: 44[提交] [状态] [讨论版] [命题人:admin] 题目描述 有一块棋盘,棋盘的边长为100000,行和列的 ...
- pip 安装出现异常
MacBookPro:~ mac$ pip install numpy Collecting numpy Downloading numpy-1.13.1-cp35-cp35m-macosx_10_6 ...
- SQLServer事务的原理
1.事务的概念 是数据库管理系统执行过程中的一个逻辑单元,由一个有限的数据库操作序列组成: 由事务开始(begin transaction)和事务结束(end transaction)之间执行的全体操 ...
- AngularJS1.X版本双向绑定九问
前言 由于工作的原因,使用angular1.x版本已经有一段时间了,虽然angualr2升级后就完全重构了,但每个版本存在也有一定的道理.话不多说,进入正题. 1.双向绑定的原理是什么? Angual ...
- BZOJ2023: [Usaco2005 Nov]Ant Counting 数蚂蚁(dp)
题意 题目描述的很清楚... 有一天,贝茜无聊地坐在蚂蚁洞前看蚂蚁们进进出出地搬运食物.很快贝茜发现有些蚂蚁长得几乎一模一样,于是她认为那些蚂蚁是兄弟,也就是说它们是同一个家族里的成员.她也发现整个 ...
- graphQL 启动报错No method or field found with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment] as the last argument), in priority order:
-------------------root.graphqls---------------------------这个文件用来定义属性字段,必须和实体类相同 文件里面的字段写错会报这个错误 com ...
- 三、Linux 系统目录结构
Linux 系统目录结构 登录系统后,在当前命令窗口下输入命令: ls / 你会看到如下图所示: 树状目录结构: 以下是对这些目录的解释: /bin:bin是Binary的缩写, 这个目录存放着最 ...
- tp5查询
TP5的EXP.批量查询.聚合查询等. <!--more--> //使用EXP条件表达式,表示后面是原生的SQL表达式 $result = Db::table('think_inno')- ...
- 【bug】【yii】配置log时,报错 Setting read-only property: yii\web\Application::log
Setting read-only property: yii\web\Application::log 配置放在了 components 外面,应该放在里面