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 ...
随机推荐
- pta 编程题7 List Leaves
其它pta数据结构编程题请参见:pta 这次的编程作业要求从上到下,从左到右输出一棵树的叶子节点,即树的层序遍历,用队列的方式来实现. 注意enqueue和dequeue函数参数为Queue & ...
- 302和VS启动后网站拒绝访问的解决方案
网页状态302代表的是重定向的意思,就是网页跳转的一种状态 网站拒绝访问的时候可以在输出窗口查看是否有内容输出,如果没有说明启动网站的端口可能被占用,在网站项目——属性——web——项目中把地址的端口 ...
- ZOJ-1654 Place the Robots---二分图最小点覆盖+构图
题目链接: https://vjudge.net/problem/ZOJ-1654 题目大意: 有一个N*M(N,M<=50)的棋盘,棋盘的每一格是三种类型之一:空地.草地.墙.机器人只能放在空 ...
- 2018.6.4 Oracle数据库预定义的异常列表
declare v_ename emp.ename%type; begin select ename into v_ename from emp where empno=&gno; dbms_ ...
- 洛谷P1220 关路灯【区间dp】
题目:https://www.luogu.org/problemnew/show/P1220 题意:给定n盏灯的位置和功率,初始时站在第c盏处. 关灯不需要时间,走的速度是1单位/秒.问把所有的灯关掉 ...
- Ubuntu使用问题解决办法
http://blog.csdn.net/ll_0520/article/details/6077913
- System.Threading
线程:定义为可执行应用程序中的基本执行单元. 应用程序域:一个应用程序内可能有多个线程. 上下文:一个线程可以移动到一个特定的上下文的实体 导入命名空间: //得到正在执行这个方法的线程 Thread ...
- 关于小程序button控件上下边框的显示和隐藏问题
问题: 小程序的button控件上下有一条淡灰色的边框,在空件上加上了样式 border:(none/0); 都没办法让button上下的的边框隐藏: 代码如下 <button class=&q ...
- 避免修改Android.mk添加cpp文件路径
手工输入项目需要编译的cpp文件到Android.mk里的缺点 1)繁琐,如果cpp文件很多,简直无法忍受 2)手工输入过程中容易出现错误 3)如果cpp文件更改名称,需要修改android.mk文件 ...
- GNU C中__attribute__
__attribute__基本介绍: 1. __attribute__ 可以设置函数属性.变量属性和类型属性. 2. __attribute__ 语法格式为:__attribute__ ((attri ...