深入理解 Java 中的 java.nio.file.FileSystems 类

java.nio.file.FileSystems 类充当了创建新文件系统的工厂。该类为我们提供了创建文件系统的方法。这些文件系统本身又充当了工厂,用于创建不同的对象,例如 Path、PathMatcher、UserPrincipalLookupService 和 WatchService。这些对象帮助我们访问文件及其文件系统中的其他对象。
语法:类声明

public final class FileSystems extends Object

让我们来看一下该类的方法:

方法

描述

getDefault()

此方法返回一个新的默认 FileSystem。

getFileSystem(URI uri)

此方法返回对现有 FileSystem 的引用。

newFileSystem(Path path, ClassLoader loader)

此方法用于构造一个新的 FileSystem,以访问该文件系统的文件内容。

newFileSystem(URI uri, Map env)

此方法用于使用给定的 URI 创建一个新的文件系统。

newFileSystem(URI uri, Map env, ClassLoader loader)

此方法用于使用给定的 URI 创建一个新的文件系统。示例 1:

Java


CODEBLOCK_5d5b7d7c

输出:

!image

示例 2:

Java


// Java Program to illustrate FileSystems Class by

// creating new file system using newFileSystem() method

// Importing URI class from java.net package

import java.net.URI;

// Importing required file classes from java.nio package

import java.nio.file.FileSystem;

import java.nio.file.FileSystems;

import java.nio.file.Path;

import java.nio.file.Paths;

// Importing Map and HashMap classes from java.util package

import java.util.HashMap;

import java.util.Map;

// Main class

public class GFG {

// Main driver method

public static void main(String[] args)

{

// Try block to check for exceptions

try {

// Creating object of Map class

// Declaring object of string types

Map env = new HashMap();

// Getting path of zip file

Path zipPath = Paths.get("ZipFile.zip");

// Creating URI from zip path received

URI Uri

= new URI("jar:file",

zipPath.toUri().getPath(), null);

// Create new file system from uri

FileSystem filesystem

= FileSystems.newFileSystem(Uri, env);

// Display message for better readability

System.out.println(

"FileSystem created successfully");

// Checking if file system is open or not

// using isOpen() method

if (filesystem.isOpen())

// Print statement

System.out.println("File system is open");

else

// Print statement

System.out.println("File system is close");

}

// Catch block to handle the exceptions

catch (Exception e) {

// Print the exception with line number

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/51815.html
点赞
0.00 平均评分 (0% 分数) - 0