Path, Paths and Files of Java

Preface Because I've been stuck by these inte...
File attribute
Paths
Path
Files
FileSystem
FileStore
Preface

Because I've been stuck by these interfaces and tool classes of java.nio these days, I checked a wave of documents and usage methods by the way. This article is more like the copy and paste of API, but I've written more output and precautions in the notes. If you can't stand the API, you can choose not to look at it. Next, I'll paste the main sources of documents

java2s: http://www.java2s.com/Tutorials/Java/java.nio.file/Files/index.htm
//Geek tutorial: https://geek-docs.com/java/java-tutorial/java-tutorials-index.html

java.nio

File attribute

  • The java.nio.attribute package contains classes related to attributes. It bundles file properties in the following six views.
    1. BasicFileAttributeView manages basic file attributes, such as creation time, last access time, last modification time, size, file type (regular file, directory, symbolic link or other) and file key (unique number of file). This view is supported on all platforms.

    2. DosFileAttributeView extends BasicFileAttributeView to access DOS specific file attributes. It provides support for checking whether files are hidden files, system files, archive files and read-only files. It is only available on DOS enabled systems, such as Microsoft Windows.

    3. POSIX represents the portable operating system interface of UNIX. PosixFileAttributeView extends BasicFileAttributeView and adds support for attributes available on systems that support the POSIX standard, such as UNIX. It allows us to manage owners, groups, and [related access] permissions.

    4. FileOwnerAttributeView manages the owner of the file.

    5. ACL represents access control list. AclFileAttributeView manages the ACL of a file.

    6. UserDefinedFileAttributeView manages a set of user-defined attributes for a file. The name of the property is a string. The value of the property can be any data type.

  • The supportsFileAttributeView() method in the FileStore class is used to determine whether the system supports the above views

  • Then the main methods to get these views are getAttribute(...) and readAttributes(...) in the Files class. Of course, setAttribute(...) must be used to set file attributes


Paths

First, I will introduce the tool class Paths, because there are two methods to generate Path objects for Path and Files; Path is often generated by Paths, or the File class has a toPath(); methods can be used

static Path get(String first, String... more) //Convert the Path string or string sequence connected to the Path string to Path, and you can get("c:/abc"); or get("c:","abc"). Note that there can be multiple parameters, String... more, representing n parameters, which is commonly used static Path get(URI uri) //Convert the given URI to a Path object


Path

Then there is the Path interface, which is used to replace the new interface of File. Although the name is Path, it can also be a File

  • First, the way of construction

    Path toPath() //File class object method -- returns a java.nio.file.Path object abstract Path getPath(String first, String... more) //FileSystem object method -- converts a Path string or a series of strings connected from a Path string to Path. /* Then there is the path tool class above. There should be some postures I don't know. Let's explore by ourselves */
  • Then there are common methods. It will be found that there is no judgment method for Path interface. In fact, more judgments and operations are in the Files tool class

    boolean isAbsolute() //Tell me if this road is absolute boolean endsWith(Path other) //Test whether this path ends with the given path boolean endsWith(String other) //Test whether the path ends with the given string, for example, "C: / A / banana / C a T" can end with "/ banana/cat", but not with "t" boolean startsWith(Path other) //Test whether this path starts with the given path. boolean startsWith(String other) //Test whether the path starts with the given string, as above Path getFileName() //Return the name of the file or directory represented by this Path as the Path object, file name or folder name, excluding the Path Path getName(int index) //Returns the name element of this Path as a Path object. The nearest root in the directory is 0, and the farthest is (count-1). Count is obtained by the following method int getNameCount() //Returns the number of name elements in the path. 0, only root Path getParent() //Return the parent path. If this path does not have a parent returning null, such as / a/b/c returning / a/b, cooperate with the following methods to eliminate "." or ".." Path normalize() //Returns a path that is the elimination of redundant name elements. If the "." and ".." are eliminated Path getRoot() //Returns the root component of this Path as a Path object, or null if the Path does not have a root component. If "c: /" is returned Path relativize(Path other) //Constructs the relative path between this path and the given path. It's a bit difficult to understand. p1 - "Topic.txt", p2 - "Demo.txt", p3 - / Java / JavaFX/Topic.txt ", p4 - / Java / 2011";; then p1 and p2 result in ".. / Demo.txt";; p2 and p1 result in ".. / Topic.txt";; p3 and p4 result in ".. /.. / 2011";; p4 and p3 result in ".. / JavaFX/Topic.txt" Path resolve(String other) //Converts the given Path string to Path. For example, the result of "c:/a/b" and "c.txt" is "c:/a/b/c.txt"; it is more like splicing Path resolveSibling(String other) //Converts the given Path string to Path. For example, the result of "c:/a/b.txt" and "c.txt" is "c:/a/c.txt"; it is more like a replacement Path subpath(int beginIndex, int endIndex) //Returns a relative Path, which is a subsequence of the name element of the Path. For example, the parameter "d:/a/b/c.txt" returns a "b/c.txt" for (1,3) Path toAbsolutePath() //Returns the Path object that represents the absolute Path of this Path. Include drive letter and filename or folder name Iterator<Path> iterator() //Returns the iterator of the name element of this path. The iterator of "c:/a/b/c.txt" can next give the following "a""b""c.txt" File toFile() //Returns the File object representing this path


Files

Finally, it is the magic Files tool class, which is mainly used with the object of Path interface

  • There are a lot of static methods for tool classes. First, they are judged:

    static boolean exists(Path path, LinkOption... options) //Test whether the file exists. static boolean notExists(Path path, LinkOption... options) //Test whether the file where this path is located does not exist. static boolean isDirectory(Path path, LinkOption... options) //Test whether the file is a directory. static boolean isExecutable(Path path) //Test whether the file is executable. static boolean isHidden(Path path) //Tells if the file is hidden. static boolean isReadable(Path path) //Test whether the file is readable. static boolean isRegularFile(Path path, LinkOption... options) //Test whether the file is a regular file with opaque content. To be honest, I don't know what regular documents mean static boolean isSameFile(Path path, Path path2) //Test if both paths find the same file. static boolean isSymbolicLink(Path path) //Test whether the file is a symbolic link. / / static boolean isWritable(Path path) //Test whether the file is writable.
  • Deleted:

    static boolean deleteIfExists(Path path) //Delete the file if it exists. static void delete(Path path) //Delete the file.
  • Duplicated:

    static long copy(InputStream in, Path target, CopyOption... options) //Copies all bytes in the input stream to a file. CopyOption is an inherited interface, mainly including enumeration classes StandardCopyOption and LinkOption. The former includes replace  existing (i.e. replace overwrite), copy  attributes (copy the file attribute information of the source file to the target file) and atomic  move (atomic copy). The latter only includes nofollow  links. Well, the latter is not Understand ( static long copy(Path source, OutputStream out) //Copies all bytes in the file to the output stream. static Path copy(Path source, Path target, CopyOption... options) //Copy the file to the destination file.
  • Moved and renamed:

    static Path move(Path source, Path target, CopyOption... options) //Move or rename the file to the destination file.
  • To create files and folders:

    static Path createDirectories(Path dir, FileAttribute<?>... attrs) //First create all non-existent parent directories to create the directory. static Path createDirectory(Path dir, FileAttribute<?>... attrs) //Create a new directory. static Path createFile(Path path, FileAttribute<?>... attrs) //Create a new and empty file if it already exists and fails.
  • Of file properties:

    static <V extends FileAttributeView> V getFileAttributeView(Path path, class<V> type, LinkOption... options) //Returns the file properties view for the given type. Specify one of the six views, which are a little to at the beginning. The obtained xxxAttributeView will have a readAttributes method with the same name as the following to get a real get operation of xxxAttributes, which is all in the object of the xxxAttributes class static <A extends BasicFileAttributes> A readAttributes(Path path, class<A> type, LinkOption... options) //Read the properties of the file as a bulk operation. Specify an xxxAttributes, get an instance, and get basic attributes such as time through the methods in it static Object getAttribute(Path path, String attribute, LinkOption... options) //Read the value of the file property. The syntax of this String attributes parameter is fixed in the form of view name: comma separated attributes; view name specifies the view name such as basic,posix,acl, etc., which is not written. If it is written, it is basic by default; if it is written, it is added with ":"; you can use "basic: *" or "*" to read all, or use "basic: size, lastModifiedTime" to read the size and modification time. The specific attributes can also be seen in the specific specified classes. For example, the basic view can see which methods are available in the BasicFileAttributes interface and which file attributes can be read. Similarly, the following String attributes are the same static Map<String,Object> readAttributes(Path path, String attributes, LinkOption... options) //Read a set of file properties as a bulk operation. static Path setAttribute(Path path, String attribute, Object value, LinkOption... options) //Sets the value of the file property. /* The following methods are also used to get attributes, but we haven't studied how to use them */ static FileTime getLastModifiedTime(Path path, LinkOption... options) //Returns the last modified time of the file. static UserPrincipal getOwner(Path path, LinkOption... options) //Returns the owner of the file. static Set<PosixFilePermission> getPosixFilePermissions(Path path, LinkOption... options) //Returns POSIX file permissions for the file. static Path setLastModifiedTime(Path path, FileTime time) //Update the last modified time attribute of the file. static Path setOwner(Path path, UserPrincipal owner) //Update file owner. static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) //Set POSIX permissions for files. static long size(Path path) //Returns the size of the file in bytes.
  • Traversing the file list (newDirectoryStream just traverses the subdirectory list of the current Path, or writes a recursive call in a method to achieve traversal to the end; walk can determine the depth of traversal through the maxDepth parameter, and the following FileVisitOption parameter is optional; list is similar to newDirectoryStream, the difference is that walk and newDirectoryStream are recursive, and list is Non recursive)

    static DirectoryStream<Path> newDirectoryStream(Path dir) //Open a directory and return a DirectoryStream to traverse all entries in the directory. It is better to use try with resources construction, which can automatically close resources. The returned DirectoryStream < Path > can directly use the Iterator or for loop to traverse the files or directories under each dir static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) //For the overload of the above method, filter is achieved by implementing parameter 2 (there is a boolean accept(Path p) method to determine whether the file meets the requirements). For example, write "return (Files.size (P) > 8192L)" in the accept method to match files larger than 8k static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) //For the overload of the above method, the corresponding file can be matched through parameter 2 as filter. For example, new directorystream (DIR, "*. java") is used to traverse files with all java suffixes in the directory static Stream<Path> walk(Path start, FileVisitOption... options) //Depth first traversal. Returns a Stream that lazily populates the Path based on the file tree of the given start file through Path. static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) //Depth first traversal. Returns a Stream that lazily populates the Path by walking through the file tree for a given start file. static Stream<Path> list(Path dir) //Returns a lazy padded Stream whose element is an entry in the Stream. The returned Stream encapsulates a DirectoryStream for traversal.
  • Read and edit the

    static BufferedReader newBufferedReader(Path path) //Open a file for reading, and return a BufferedReader to read the text from the file in an efficient way. static BufferedReader newBufferedReader(Path path, Charset cs) //Open a file for reading and return a BufferedReader, which can be used to read text from the file in an effective way. static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options) //Open or create a write file, return a BufferedWriter, which can be used to write text to the file in an effective way. static BufferedWriter newBufferedWriter(Path path, OpenOption... options) //Open or create a write file and return a BufferedWriter to write to the file in an efficient way. static SeekableByteChannel newByteChannel(Path path, OpenOption... options) //Open or create a file and return an accessible byte channel to access the file. static SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) //Open or create a file and return an accessible byte channel to access the file. static InputStream newInputStream(Path path, OpenOption... options) //Open a file and return to the input stream to read from it. static OutputStream newOutputStream(Path path, OpenOption... options) //Opens or creates a file that returns the output stream that can be used to write bytes to the file. static byte[] readAllBytes(Path path) //Reads all bytes in the file. static List<String> readAllLines(Path path) //Read all lines from the file. static List<String> readAllLines(Path path, Charset cs) //Read all lines from the file. static Path write(Path path, byte[] bytes, OpenOption... options) //Writes bytes to a file. static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) //Writes a line of text to a file. static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) //Writes a line of text to a file.


FileSystem

The getDefault() of the FileSystems tool class is often used to generate the default instance, and then make some judgments with the FileStore. What's the use of this


FileStore

The file storage pool is mainly used to detect whether the file system supports some operations and obtain some properties of the file system

  • It can be obtained through getFileStores() of FileSystem

  • Some common interface methods

    abstract boolean supportsFileAttributeView(class<? extends FileAttributeView> type) //Tells this file store whether it supports file properties identified by the given file properties view. abstract boolean supportsFileAttributeView(String name) //Tells this file store whether it supports file properties identified by the given file properties view.

11 February 2020, 04:52 | Views: 2234

Add new comment

For adding a comment, please log in
or create account

0 comments