📜  Java的.nio.file.Paths类在Java中

📅  最后修改于: 2022-05-13 01:55:43.886000             🧑  作者: Mango

Java的.nio.file.Paths类在Java中

Java.nio.file.Paths 类包含将路径字符串或 URI 转换为 Path 的静态方法。

类声明:

public final class Paths
extends Object

方法:

MethodDescription

get(String first, String… more) 

This method converts a path string, or a sequence of strings that when joined form a path string, to a Path.



get(URI uri)

This method converts the given URI to a Path object.

1. public static Path get(String first, String… more):

通过将给定的字符串转换为路径来返回路径。如果“more”没有指定任何字符串,则“first”是唯一要转换的字符串。如果“more”指定额外的字符串,则“first”是序列的初始部分,额外的字符串将附加到“first”之后,以“/”分隔。

参数:

  1. 第一 - 路径的初始部分。
  2. more – 要加入路径的额外字符串。

返回:结果路径

抛出:

InvalidPathException – 如果给定的字符串无法转换为路径



Java
// Java program to demonstrate
// java.nio.file.Path.get(String first,String... more)
// method
  
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        // create object of Path
        Path path = (Path)Paths.get("/usr", "local", "bin");
  
        // print Path
        System.out.println(path);
    }
}


Java
// Java program to demonstrate
// java.nio.file.Path.get(URI uri) method
  
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
  
public class Path {
    public static void main(String[] args)
        throws IOException, URISyntaxException
    {
        String uribase = "https://www.geeksforgeeks.org/";
        // Constructor to create a new URI
        // by parsing the string
        URI uri = new URI(uribase);
  
        // create object of Path
        Path path = (Path)Paths.get(uri);
  
        // print ParentPath
        System.out.println(path);
    }
}


输出
/usr/local/bin

2.public static Path get(URI uri):通过将给定的Uri转换为Path,返回一个Path。

参数:

  • uri——要转换

返回:结果路径

抛出:

  1. IllegalArgumentException – 如果 URI 的参数不合适
  2. FileSystemNotFoundException – 如果由 URI 标识的文件系统不存在
  3. SecurityException – 如果安全管理器拒绝访问文件系统

Java

// Java program to demonstrate
// java.nio.file.Path.get(URI uri) method
  
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;
  
public class Path {
    public static void main(String[] args)
        throws IOException, URISyntaxException
    {
        String uribase = "https://www.geeksforgeeks.org/";
        // Constructor to create a new URI
        // by parsing the string
        URI uri = new URI(uribase);
  
        // create object of Path
        Path path = (Path)Paths.get(uri);
  
        // print ParentPath
        System.out.println(path);
    }
}

输出:

https://www.geeksforgeeks.org/