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 ...
随机推荐
- JavaScript: apply , call 方法
我在一开始看到javascript的函数apply和call时,非常的模糊,看也看不懂,最近在网上看到一些文章对apply方法和call的一些示例,总算是看的有点眉目了,在这里我做如下笔记,希望和大家 ...
- iptables (1) 原理
网上看到这个配置讲解得还比较易懂,就转过来了,大家一起看下,希望对您工作能有所帮助. iptables简介 netfilter/iptables(简称为iptables)组成Linux平台下的包过滤防 ...
- cd ..和cd -
cd ..是返回上一层目录, cd -是返回到上一次的工作目录.
- CUDA:Supercomputing for the Masses (用于大量数据的超级计算)-第二节
原文链接 第二节:第一个内核 Rob Farber 是西北太平洋国家实验室(Pacific Northwest National Laboratory)的高级科研人员.他在多个国家级的实验室进行大型并 ...
- Drupal的入门学习
1. 注意content中的区别 Article和Basic page的区别 a.输入字段不一样,Article内容多了两个字段:tag和图片. b.内容的默认设置不一样,Article默认允许评论, ...
- 理解Express 中间件
Express 中间件 Express程序基本上是一系列中间件函数的调用.中间件就是一个函数, 接受 req.res.next几个参数. 中间件函数可以执行任何代码, 对请求和响应对象进行修改, 结束 ...
- 1143: [CTSC2008]祭祀river
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 4018 Solved: 2048[Submit][Status][Discuss] Descript ...
- Java读取各种文件格式内容
所需的jar包哦也不要太记得了,大家可以搜搜,直接上代码: import java.io.BufferedInputStream; import java.io.File; import java.i ...
- g++编译器的使用(转载)
关于g++ g++ 是GNU组织开发出的编译器软件集合(GCC)下的一个C++编译器.它是Unix 和 Linux 系统下标配的 基于命令行的 C++编译器.如果你的系统是Windows,可以按照 ...
- A计划 hdu2102(BFS)
A计划 hdu2102 可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验.魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老.年迈的国 ...