The Java NiO path interface and the files class work together to manipulate file instances

Path interface

1. Path represents a directory name sequence, followed by a file name. When the first part in the path is the root part, it is the absolute path, such as / or C: \, and the root part allowed to access depends on the file system;

2. The path starting with the root component is an absolute path, otherwise it is a relative path;

3. Static paths The get method accepts one or more strings, and the strings are automatically connected using the path separator of the default file system (UNIX is /, windows is \), which solves the cross platform problem. Then, analyze the connected results. If it is not a legal path, throw an invalidpathexception exception, otherwise, return a path object;

4. Get path object from string path

Get can also obtain an entire path (that is, a single string composed of multiple parts), for example, read the path from the configuration file:

5. Combine or resolve paths

1) Calling p.resolve (q) will return a path according to the following rules: if q is an absolute path, it will return Q; otherwise, the appended path will return P / Q or P \ Q

2) Calling p.resolvesibling ("Q") will resolve the parent path o of the specified path P and generate the sibling path O / Q

3) Calling P. relativize (R) will generate a redundant path Q, parsing Q will generate a relative path R, and finally r does not contain the intersection path with P

4) Toabsolutepath will produce the absolute path of the given path, starting from the root part

5) The path class also has some useful methods for breaking and combining paths, such as GetParent, getfilename and getroot / / to obtain the root directory

6) Path has a tofile method to deal with the legacy file class, and the file class also has a topath method

Files utility class

1. Read write file

Method signature:

static path write(Path path,byte[] bytes,OpenOption... options)

static path write(Path path,Iterable lines,OpenOption... options)

Only the following methods are listed here. For more methods, please see the API document

Openoption is a NiO interface, and standardopenoption is its enumeration implementation class. Please check the API documentation for each enumeration instance function

2. Copy, cut, delete

Method signature:

static path copy(Path source,Path target,CopyOption... options)

static path move(Path source,CopyOption... options)

Static void delete (path) / / if the path file does not exist, an exception will be thrown. It is better to call the following at this time

static boolean deleteIfExists(Path path)

Only the following methods are listed here. For more methods, please see the API document

Copyoption is a NiO interface, and standardcopyoption is its enumeration implementation class. Please check the API documentation for each enumeration instance function

One of them is atomic_ Move can be filled in to ensure the atomic operation. Either the move is completed successfully or the source file remains in the original location

3. Create files and directories

4. Get file information

For details, see the API document or corejava page51

5. Iterate over files in directory

The old file class has two methods to obtain the string array composed of all files in the directory, string [] list () and string [] list (filefilter filter). However, when the directory contains a large number of files, the performance of these two methods will be very low.

Cause analysis:

At this time, high technology comes -- files obtains an iterative directory stream,

Pass in a directory path, traverse the descendant directory, and return a stream of directory path. Note that all paths involved here are directories rather than files!

Therefore, the files class designs newdirectorystream (path DIR) and its overloaded method to generate iteratable objects (foreach iteration is available)

Traverse the directory to get an iterative collection of descendant files

Return a directory stream, which can be regarded as a collection with all paths stored and implemented iteratable,

Therefore, iterators or foreach can be used to iterate, but when using iterators, be careful not to invoke another iterator:

While DirectoryStream extends Iterable,it is not a general-purpose Iterable as it supports only a single Iterator; invoking the iterator method to obtain a second or subsequent iterator throws IllegalStateException.

Example:

You can pass in the glob parameter, that is, use the glob mode to filter files (instead of list (filefilter)):

Newdirectorystream (path dir, string glob) note that it is a string type

Glob mode

The so-called glob pattern refers to the simplified regular expressions used by the shell.

1. The asterisk * matches 0 or more characters of the path component; For example, * Java matches all java files in the current directory

2. Two star * * matches 0 or more characters across the directory boundary; For example * * Java matches java files in all subdirectories

3. The question mark (?) matches only one character; for example,??. Java matches all four character java files, excluding the extension; use?, because * is a wildcard and does not specify the number

4.[...] To match a character set, you can use the line [0-9] and the negator [! 0-9]; For example, test [0-9a-f] Java matches testx Java, assuming that x is a hexadecimal number, [0-9a-f] is a hexadecimal number matching a single character, such as B (hexadecimal is not case sensitive)

If two characters are separated by a dash in square brackets, it means that all within the range of these two characters can be matched (for example, [0-9] means that all numbers from 0 to 9 are matched).

5.{...} Match one of multiple options separated by commas; For example, * {Java, class} matches all java files and class files

6. \ escape characters in any of the above modes; For example, * \ * * matches files whose file names contain * in all subdirectories. Here is * * escape, preceded by 0 or more characters

The following is the glob model summarized by netizens:

Is it not cool to iterate through all the descendant file sets of a directory? Let's directly traverse all descendants of a directory (including directories and files)

We can call the walkfiletree method of files class and pass in an object of filevisitor interface type (there are more methods waiting for you to find in the API...)

Let's summarize,

Files. Newdirectorystream (path DIR) traverses and returns an iteratable collection of descendant files;

Files. Walkfiletree (path dir, filevisitor FV) is a process of traversing directories and files;

Zip file system

As we know from the above, the paths class will find the path in the default file system, that is, the file on the user's local disk.

In fact, we can also have other file systems, such as zip file system.

The above code will establish a zipname based file system that contains all the files in the zip document.

1) If you know the file name (string type), it is easy to copy the file from the zip document:

Q:fs. Getpath uses the zip file system to getpath. Can the default file system be called?

A: Yes. There is a static getdefault () method in the file system class, which returns a default file system object, which can also be determined by the file name getpath.

Whether getpath (string name) is traversal or random access, go to the source code implementation when you have time.

2) To list all the files in the zip document, you can also use walkfiletree to traverse the file tree

The above example of the cooperative operation file of Java NiO path interface and files class is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>