# 如何创建路径 – Java NIO

> 原文： [https://howtodoinjava.com/java7/nio/how-to-define-path-in-java-nio/](https://howtodoinjava.com/java7/nio/how-to-define-path-in-java-nio/)

众所周知，Java SE 7 发行版中引入的[**`Path`**](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html "NIO Path")类是`java.nio.file`包的主要入口点之一。 如果您的应用程序使用 NIO，则应了解有关此类中可用特性的更多信息。 我开始[**NIO 教程**](//howtodoinjava.com/java-nio-tutorials/ "Java NIO Tutorials")，并[定义 NIO 2 中的路径](//howtodoinjava.com/java-nio-tutorials/ "Java NIO Tutorials")。

![java nio](img/530c6a1ae9a53e40c90c35ccaff0f7ab.png)

在本教程中，我列出了在 NIO 中创建`Path`的 6 种方法。

**注意**：我正在为以下位置的文件构建路径-“`C:/Lokesh/Setup/workspace/NIOExamples/src/sample.txt`”。 我已经事先创建了此文件，并将在以下示例中创建此文件的路径。

```java
Section in this post:

Define absolute path
Define path relative to file store root
Define path relative to current working directory
Define path from URI scheme
Define path using file system default
Using System.getProperty() to build path
```

让我们一一看一下以上所有技术的示例代码：

## 定义绝对路径

绝对路径始终包含根元素和查找文件所需的完整目录列表。 不再需要更多信息来访问文件或路径。 我们将使用带有以下签名的`getPath()`方法。

```java
/**
* Converts a path string, or a sequence of strings that when joined form a path string,
* to a Path. If more does not specify any elements then the value of the first parameter
* is the path string to convert. If more specifies one or more elements then each non-empty
* string, including first, is considered to be a sequence of name elements and is
* joined to form a path string.
*/
public static Path get(String first, String… more);
```

让我们看下面的代码示例。

```java
//Starts with file store root or drive
Path absolutePath1 = Paths.get("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");
Path absolutePath2 = Paths.get("C:/Lokesh/Setup/workspace", "NIOExamples/src", "sample.txt");
Path absolutePath3 = Paths.get("C:/Lokesh", "Setup/workspace", "NIOExamples/src", "sample.txt");

```

## 定义相对于文件存储根的路径

相对于文件存储根的路径以正斜杠（“`/`”）字符开头。

```java
//How to define path relative to file store root (in windows it is c:/)
Path relativePath1 = FileSystems.getDefault().getPath("/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");
Path relativePath2 = FileSystems.getDefault().getPath("/Lokesh", "Setup/workspace/NIOExamples/src", "sample.txt");

```

## 定义相对于当前工作目录的路径

要定义相对于当前工作目录的 NIO 路径，请不要同时使用文件系统根目录（在 Windows 中为`c:/`）或斜杠（“`/`”）。

```java
//How to define path relative to current working directory
Path relativePath1 = Paths.get("src", "sample.txt");

```

## 定义 URI 方案的路径

并不经常，但是有时我们可能会遇到这样的情况，我们想将格式为“`file:///src/someFile.txt`”的文件路径转换为 NIO 路径。 让我们来看看如何做。

```java
        //URI uri = URI.create("file:///c:/Lokesh/Setup/workspace/NIOExamples/src/sample.txt"); //OR
	URI uri = URI.create("file:///Lokesh/Setup/workspace/NIOExamples/src/sample.txt");

	String scheme =  uri.getScheme();
	if (scheme == null)
		throw new IllegalArgumentException("Missing scheme");

	//Check for default provider to avoid loading of installed providers
	if (scheme.equalsIgnoreCase("file"))
	{
		System.out.println(FileSystems.getDefault().provider().getPath(uri).toAbsolutePath().toString());
	}

	//If you do not know scheme then use this code. This code check file scheme as well if available.
	for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
		if (provider.getScheme().equalsIgnoreCase(scheme)) {
			System.out.println(provider.getPath(uri).toAbsolutePath().toString());
			break;
		}
	}

```

## 使用文件系统默认值定义路径

这是上述示例的另一种变体，其中可以使用`FileSystems.getDefault().getPath()`方法代替使用`Paths.get()`。
绝对路径和相对路径的规则与上述相同。

```java
FileSystem fs = FileSystems.getDefault();
Path path1 = fs.getPath("src/sample.txt");
Path path2 = fs.getPath("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");

```

## 使用`System.getProperty()`构建路径

好吧，这是不可能的，但是很高兴知道。 您还可以使用系统特定的`System.getProperty()`来构建特定文件的路径。

```java
Path path1 = FileSystems.getDefault().getPath(System.getProperty("user.home"), "downloads", "somefile.txt");

```

因此，这是创建 NIO 路径的 6 种方法。 让我们合并并运行它们以检查其输出。

```java
package com.howtodoinjava.nio;

import static java.nio.file.FileSystems.getDefault;

import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.spi.FileSystemProvider;

public class WorkingWithNIOPath 
{
	public static void main(String[] args)
	{
		 defineAbsolutePath();
		 defineRelativePathToRoot();
		 defineRelativePathToWorkingFolder();
		 definePathFromURI();
		 UsingFileSystemGetDefault();
		 UsingSystemProperty();
	}

	//Starts with file store root or drive
	private static void defineAbsolutePath() 
	{
		//Starts with file store root or drive
		Path absolutePath1 = Paths.get("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");
		Path absolutePath2 = Paths.get("C:/Lokesh/Setup/workspace", "NIOExamples/src", "sample.txt");
		Path absolutePath3 = Paths.get("C:/Lokesh", "Setup/workspace", "NIOExamples/src", "sample.txt");

		System.out.println(absolutePath1.toString());
		System.out.println(absolutePath2.toString());
		System.out.println(absolutePath3.toString());
	}

	//Starts with a "/"
	private static void defineRelativePathToRoot() 
	{
		//How to define path relative to file store root (in windows it is c:/)
		Path relativePath1 = FileSystems.getDefault().getPath("/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");
		Path relativePath2 = FileSystems.getDefault().getPath("/Lokesh", "Setup/workspace/NIOExamples/src", "sample.txt");

		System.out.println(relativePath1.toAbsolutePath().toString());
		System.out.println(relativePath2.toAbsolutePath().toString());
	}

	//Starts without a "/"
	private static void defineRelativePathToWorkingFolder() 
	{
		//How to define path relative to current working directory
		Path relativePath1 = Paths.get("src", "sample.txt");
		System.out.println(relativePath1.toAbsolutePath().toString());
	}

	private static void definePathFromURI() 
	{
		//URI uri = URI.create("file:///c:/Lokesh/Setup/workspace/NIOExamples/src/sample.txt"); //OR
		URI uri = URI.create("file:///Lokesh/Setup/workspace/NIOExamples/src/sample.txt");

		String scheme =  uri.getScheme();
        if (scheme == null)
            throw new IllegalArgumentException("Missing scheme");

        //check for default provider to avoid loading of installed providers
        if (scheme.equalsIgnoreCase("file"))
            System.out.println(FileSystems.getDefault().provider().getPath(uri).toAbsolutePath().toString());

        // try to find provider
        for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
            if (provider.getScheme().equalsIgnoreCase(scheme)) {
            	System.out.println(provider.getPath(uri).toAbsolutePath().toString());
            	break;
            }
        }
	}

	private static void UsingFileSystemGetDefault() {
		FileSystem fs = getDefault();
		Path path1 = fs.getPath("src/sample.txt");
		Path path2 = fs.getPath("C:/Lokesh/Setup/workspace/NIOExamples/src", "sample.txt");

		System.out.println(path1.toAbsolutePath().toString());
		System.out.println(path2.toAbsolutePath().toString());
	}

	private static void UsingSystemProperty() {
		 Path path1 = FileSystems.getDefault().getPath(System.getProperty("user.home"), "downloads", "somefile.txt");
		 System.out.println(path1.toAbsolutePath().toString());
	}

}

Output in console:

****defineAbsolutePath****
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
****defineRelativePathToRoot****
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
****defineRelativePathToWorkingFolder****
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
****definePathFromURI****
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
****UsingFileSystemGetDefault****
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
C:LokeshSetupworkspaceNIOExamplessrcsample.txt
****UsingSystemProperty****
C:Usershug13902downloadssomefile.txt

```

**祝您学习愉快！**