Java NIO Path

The Java Path interface is part of the Java NIO 2 update which Java NIO received in Java 6 and Java 7. The Java Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path.

A Java Path instance represents a path in the file system. A path can point to either a file or a directory. A path can be absolute or relative. An absolute path contains the full path from the root of the file system down to the file or directory it points to. A relative path contains the path to the file or directory relative to some other path. Relative paths may sound a bit confusing. Don‘t worry. I will explain relative paths in more detail later in this Java NIO Path tutorial.

Do not confuse a file system path with the path environment variable in some operating systems. The java.nio.file.Path interface has nothing to do with the path environment variable.

In many ways the java.nio.file.Path interface is similar to the java.io.File class, but there are some minor differences. In many cases though, you can replace the use of the File class with use of the Path interface.

Creating a Path Instance

In order to use a java.nio.file.Path instance you must create a Path instance. You create a Path instance using a static method in the Paths class (java.nio.file.Paths) named Paths.get(). Here is a Java Paths.get() example:

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathExample {

    public static void main(String[] args) {

        Path path = Paths.get("c:\\data\\myfile.txt");

    }
}

Notice the two import statements at the top of the example. To use the Path interface and the Paths class we must first import them.

Second, notice the Paths.get("c:\\data\\myfile.txt") method call. It is the call to the Paths.get() method that creates the Path instance. The Paths.get() method is a factory method for Path instances, in other words.

Creating an Absolute Path

Creating an absolute path is done by calling the Paths.get() factory method with the absolute file as parameter. Here is an example of creating a Path instance representing an absolute path:

Path path = Paths.get("c:\\data\\myfile.txt");

The absolute path is c:\data\myfile.txt. The double \ characters are necessary in Java strings, since the \ is an escape character, meaning the following character tells what character is really to be located at this place in the string. By writing \\ you tell the Java compiler to write a single \ character into the string.

The above path is a Windows file system path. On a Unix system (Linux, MacOS, FreeBSD etc.) the above absolute path could look like this:

Path path = Paths.get("/home/jakobjenkov/myfile.txt");

The absolute path is now /home/jakobjenkov/myfile.txt .

If you used this kind of path on a Windows machine (a path starting with /) the path would be interpreted as relative to the current drive. For instance, the path

/home/jakobjenkov/myfile.txt

could be interpreted as being located on the C drive. Then the path would correspond to this full path:

C:/home/jakobjenkov/myfile.txt

Creating a Relative Path
A relative path is a path that points from one path (the base path) to a directory or file. The full path (the absolute path) of a relative path is derived by combining the base path with the relative path.

The Java NIO Path class can also be used to work with relative paths. You create a relative path using the Paths.get(basePath, relativePath) method. Here are two relative path examples in Java:

Path projects = Paths.get("d:\\data", "projects");

Path file     = Paths.get("d:\\data", "projects\\a-project\\myfile.txt");

The first example creates a Java Path instance which points to the path (directory) d:\data\projects. The second example creates a Path instance which points to the path (file) d:\data\projects\a-project\myfile.txt .

When working with relative paths there are two special codes you can use inside the path string. These codes are:

  • .
  • ..

The . code means "current directory". For instance, if you create a relative path like this:

Path currentDir = Paths.get(".");
System.out.println(currentDir.toAbsolutePath());

Then the absolute path the Java Path instance corresponds to will be the directory in which the application executing the above code is executed.

If the . is used in the middle of a path string it just means the same directory as the path was pointing to at that point. Here is an Path example illustrating that:

Path currentDir = Paths.get("d:\\data\\projects\.\a-project");

This path will correspond to the path:

d:\data\projects\a-project

The .. code means "parent directory" or "one directory up". Here is a Path Java example illustrating that:

Path parentDir = Paths.get("..");

The Path instance created by this example would correspond to the parent directory of the directory from which the application running this code was started.

If you use the .. code in the middle of a path string it will correspond to changing one directory up at that point in the path string. For instance:

String path = "d:\\data\\projects\\a-project\\..\\another-project";
Path parentDir2 = Paths.get(path);

The Java Path instance created by this example will correspond to this absolute path:

d:\data\projects\another-project

The .. code after the a-project directory changes directory up the the parent directory projects and then the path references down into the another-project directory from there.

The . and .. codes also work in combination with the two-string Paths.get() method. Here are two Java Paths.get() examples showing simple examples of that:

Path path1 = Paths.get("d:\\data\\projects", ".\\a-project");

Path path2 = Paths.get("d:\\data\\projects\\a-project",
                       "..\\another-project");

There are more ways that the Java NIO Path class can be used to work with relative paths. You will learn more about that later in this tutorial.

Path.normalize()

The normalize() method of the Path interface can normalize a path. Normalizing means that it removes all the . and .. codes in the middle of the path string, and resolves what path the path string refers to. Here is a Java Path.normalize() example:

String originalPath =
        "d:\\data\\projects\\a-project\\..\\another-project";

Path path1 = Paths.get(originalPath);
System.out.println("path1 = " + path1);

Path path2 = path1.normalize();
System.out.println("path2 = " + path2);

This Path example first creates a path string with a .. code in the middle. Then the example creates a Path instance from this path string, and prints that Path instance out (actually it prints Path.toString()).

The example then calls normalize() on the created Path instance, which returns a new Path instance. This new, normalized Path instance is then also printed out.

Here is the output printed from the above example:

path1 = d:\data\projects\a-project\..\another-project
path2 = d:\data\projects\another-project

As you can see, the normalized path does not contain the a-project\.. part, as this is redundant. The removed part adds nothing to the final absolute path.

原文地址:https://www.cnblogs.com/winner-0715/p/8545150.html

时间: 2024-10-13 07:21:43

Java NIO Path的相关文章

Java NIO 完全学习笔记(转)

本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java NIO,被称为新 IO(New IO),是 Java 1.4 引入的,用来替代 IO API的. Java NIO:Channels and Buffers 标准的 Java IO API ,你操作的对象是字节流(byte stream)或者字符流(character stream),而 NIO,你操

Java NIO 学习总结 学习手册

原文 并发编程网(翻译):http://ifeve.com/java-nio-all/  源自 http://tutorials.jenkov.com/java-nio/index.html Java NIO: Channels and Buffers(通道和缓冲区) 标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中. Java NIO: Non-blocking IO(非阻塞IO

5种调优Java NIO和NIO.2的方式

Java NIO(New Input/Output)——新的输入/输出API包——是2002年引入到J2SE 1.4里的.Java NIO的目标是提高Java平台上的I/O密集型任务的性能.过了十年,很多Java开发者还是不知道怎么充分利用NIO,更少的人知道在Java SE 7里引入了更新的输入/输出 API(NIO.2).这篇教程展示了5个在Java编程的一些常见场景里使用NIO和NIO.2包的简单示例. NIO和NIO.2对于Java平台最大的贡献是提高了Java应用开发中的一个核心组件的

Java NIO、NIO.2学习笔记

相关学习资料 http://www.molotang.com/articles/903.html http://www.ibm.com/developerworks/cn/education/java/j-nio/j-nio.html 目录 1. NIO.NIO.2简介 2. NIO中的关键技术 1. NIO.NIO.2简介 Java中的输入流.输出流都是阻塞式的输入.输出.不仅如此,传统的输入流.输出流都是通过字节的移动来处理的(即使是字符流,在底层也是通过字节流来进行处理的),也就是说,面向

Java NIO try-with-resources [ 转载 ]

Java NIO try-with-resources [ 转载 ] @原文链接 http://blog.csdn.net/jackiehff/article/details/17765909     try-with-resources语句是一个声明一个或多个资源的 try 语句.一个资源作为一个对象,必须在程序结束之后随之关闭. try-with-resources语句确保在语句的最后每个资源都被关闭 .任何实现了 java.lang.AutoCloseable的对象, 包括所有实现了 ja

java 7 使用java.nio.file.*操作文件

java7中辅助类Files新增了两个方法用于读去文件的全部行和全部字节.So..再也不用缓冲区了. 1 package java8_test; 2 3 import java.io.IOException; 4 import java.nio.file.Files; 5 import java.nio.file.Path; 6 import java.nio.file.Paths; 7 import java.util.List; 8 9 public class TestMain { 10

运行报错:Unable to execute dex: java.nio.BufferOverflowException

今天在网上下载了一个Demo,导入运行时报错,信息如下: [2015-03-01 21:09:24 - Dex Loader] Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace. [2015-03-01 21:09:24 - BinderService] Conversion to Dalvik format failed: Unable to execut

Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.(转)

1.程序运行后异常显示: 解决方案:在项目上点击右键->properties->Java Build Path, remove掉Android Dependences即可 Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.(转),布布扣,bubuko.com Unable to execute dex: java.nio.BufferOverflowExc

Java NIO总结

一.NIO NIO是new IO,也是非阻塞IO.有Channel.Selector.Buffer.Pipe.FileLock等类. Buffer在java.nio包 Channel.Selector.Pipe.FileLock等在java.nio.channels包 二.Channel通道 设置非阻塞configureBlocking(false); 注册选择器register(selector,SelectionKey.OP_XXX) 使用方法read(Buffer) ,write(Buff