Notes: I/O Stream-file operations,

Source: Internet
Author: User

Notes: I/O Stream-file operations,

The Java library uses the Path and Files classes to encapsulate all the functions required to process the file system on the user's machine. You can use Paths to obtain a specific Path object to represent a specific Path.

  • If q is an absolute path, the returned result is q.
  • Otherwise, p is followed by q As the result according to the rules of the file system.

Path relative = Paths. get ("/opt ");

System. out. println ("relative path" + relative );

Path workRelative = relative. resolve ("work ");

System. out. println ("workRelative path" + workRelative );

The output path workRelative is "\ opt \ work". There is also a convenient resolveSibling method. It parses the parent path of the specified path to generate its sibling path. The sample code is as follows:

Path tempPath = workRelative. resolveSibling ("temp ");

System. out. println ("resolveSibling path" + tempPath );

The output path tempPath is "\ opt \ temp". To generate a relative path, call the relativize method. This method returns the relative path between the specified paths. The sample code is as follows:

Path relativize = workRelative. relativize (tempPath );

System. out. println ("relativize source path \" "+ workRelative +" \ "relativize path \""

+ TempPath + "\" result path \ "" + relativize + "\"");

The output result is "relativize source path" \ opt \ work "relativize path" \ opt \ temp "result path ".. \ temp "", you can see that the relative path is returned. The normalize method of the opposite operation will remove the relative method. The sample code is as follows:

Path normalizeSourcePath = Paths. get ("/opt", "work/../test ");

System. out. println ("normalize source path \" "+ normalizeSourcePath +" \ "result path \""

+ NormalizeSourcePath. normalize () + "\"");

The output result is "normalize source path" \ opt \ work \ .. \ test "result path" \ opt \ test "".

  • File
    • Read/write files

      Files can make operations on common Files quick. For example, you can easily read all the content of a file using the readAllBytes method:

      Byte {] bytes = Files. readAllBytes (path );

      If you want to read a file as a String, you can use the String type for instantiation after calling the readAllBytes method. The following code:

      String content = newString (bytes, charset );

      To read a file as a row sequence, you can call the following code:

      List <String> lines = Files. readAllLines (path );

      To write a string to a file, you can call the following code:

      Files. write (path, content. getBytes (charset ));

      // Append content to the file

      Files. write (path, content. getBytes (charset), StandardOpenOption. APPEND );

      Files. write (path, lines );

      The preceding method is applicable to processing medium-length files. If the file to be processed is too long or a binary file, you should use a well-known stream or reader/writer. The sample code is as follows:

      InputStream in = Files. newInputStream (path );

      OutputStream out = Files. newOutputStream (path );

      Reader in = Files. newBufferedReader (path );

      Writer out = Files. newBufferedWriter (path );

    • Copy, move, and delete objects

      You can directly call

      Files. copy (fromPath, toPath );

      Mobile files can be called

      Files. move (fromPath, toPath );

      If the target path already exists, copying or moving will fail. If you want to overwrite the existing target path, you can use the REPLACE_EXISTING option and copy all the file attributes using the COPY_ATTRIBUTES option, the sample code is as follows:

      Files. copy (fromPath, toPath, StandardCopyOption. REPLACE_EXISTING,

      StandardCopyOption. COPY_ATTRIBUTES );

      You can define a mobile operation as atomic. This ensures that either the file is moved or the file is kept in the same place. You can use StandardCopyOption. ATOMIC_MOVE. The Code is as follows:

      Files. move (fromPath, toPath, StandardCopyOption. ATOMIC_MOVE );

      Finally, you can call the delete method to delete a file. If the file does not exist, an exception is thrown. The Code is as follows:

      Files. delete (path );

      If you do not want to throw an exception when the file does not exist, you can use the deleteIfExists method. This method can also be used to delete an empty directory. The Code is as follows:

      Boolean deleted = Files. deleteIfExists (path );

    • Create files and directories

      You can call the createDirectory method to create a new directory. The path parameter of this method exists only when the last part exists. If you want to create a directory in the middle of the path, you should use the createDirectories method. If you create an empty file, you can use the createFile method. If the file already exists, an exception is thrown. The sample code is as follows:

      Files. createDirectory (path );

      Files. createDirectories (path );

      Files. createFile (path );

      Some convenient methods can be used to create temporary files or directories at a specified location or system. The Code is as follows:

      Path tempDirFile = Files. createTempFile (dirPath, "tt", ". tmp ");

      Path systemTempFile = Files. createTempFile ("sys", ". tmp ");

      System. out. println ("Temp1 =" + tempDirFile + "\ tTemp2 =" + systemTempFile );

      Path tempDirPath = Files. createTempDirectory (dirPath, "dir ");

      Path systemTempDirPath = Files. createTempDirectory ("sys ");

      System. out. println ("Temp1 =" + tempDirPath + "\ tTemp2 =" + systemTempDirPath );

    • Get File Information

      Files provides some static methods to obtain file information and attributes. The method is as follows:

      • Exists: Check whether the path file or directory exists
      • IsHidden: Check whether the path file or directory is hidden.
      • IsReadable: Check whether the path file or directory is read-only
      • IsWritable: Check whether the path file is writable.
      • IsExecutable: Check whether the path file is executable
      • IsRegularFile: Check whether the path file is a regular file
      • IsDirectory: Check whether the path is a directory
      • IsSymbolicLink: Check whether the path is a symbolic connection file
      • Size: the number of bytes of the returned file.
      • GetOwner: returns the object owner.

      All file systems report a basic property set which is encapsulated in the BasicFileAttributes interface. The basic file attributes include:

      • The time when the file is created, accessed, and modified is represented by the java. nio. file. attribute. FileTime class.
      • Files are conventional files, directories, or symbolic connections, or none of them are
      • File Size

      To obtain these attributes, the call code is as follows:

      BasicFileAttributes basicAttributes = Files. readAttributes (filePath, BasicFileAttributes. class );

    • Files in the iteration directory

      The Files class sets a method to generate an Iterable object. The entire object can be used to traverse all Files in the directory. The sample code is as follows:

      DirPath = Paths. get ("d :\\", "directories", "TempDir ");

      Try (DirectoryStream <Path> entries = Files. newDirectoryStream (dirPath )){

      For (Path p: entries ){

      BasicFileAttributes attributes = Files. readAttributes (p, BasicFileAttributes. class );

      System. out. println ("path =" + p + "\ tisDirectory =" + attributes. isDirectory ()

      + "\ Tsize =" + attributes. size ());

      }

      }

      The try statement block is used to ensure that the directory stream can be properly closed. There is no specific order to access the items in the directory. You can also use the glob mode to filter files. The sample code is as follows:

      Try (DirectoryStream <Path> entries = Files. newDirectoryStream (dirPath, "*. java ")){

      // Process the code

      }

Mode

Description

Example

*

The matching path consists of 0 or more characters.

*. Java matches all java files in the current directory.

**

Matches zero or multiple characters across directory boundaries

**. Java matches java files in all subdirectories.

?

Match one character

???. Java matches all three characters in a java File

[…]

Match a character set. You can use the line character [0-9] and the inverse character [! 0-9]

Test [0-9]. java matches testx. java, where x indicates the number 0-9

{...}

Match one of multiple options separated by commas

*. {Java, class} matches all java files and class files.

\

Escape characters in any of the above modes

* \ ** Match all objects whose names contain *

If you want to access all the child members of a directory, you can call the tranquility filetree method and pass a FileVisitor-type object to it. This object is used to process file notifications, as described below:

The visitFile method will be notified when a file or directory is encountered.

The preVisitDirectory method is notified before a directory is processed.

After a directory is processed, the postVisitDirectory method is notified.

If an error occurs when you try to access a file or directory, the visitFileFailed method is notified and the subsequent operation is determined based on the returned result. The returned results include:

  • FileVisitResult. CONTINUE: CONTINUE to access the next file
  • FileVisitResult. SKIP_SUBTREE: continue to access, but no longer access any items in the entire directory
  • FileVisitResult. SKIP_SIBLINGS: continue to access, but no longer access the entire file's sibling File
  • FileVisitResult. TERMINATE: TERMINATE access

The sample code is as follows:

Files. Program filetree (dirPath, new SimpleFileVisitor <Path> (){

@ Override

Public FileVisitResult preVisitDirectory (Path dir, BasicFileAttributes attrs) throws IOException {

System. out. println ("preVisitDirectory path =" + dir );

Return FileVisitResult. CONTINUE;

}

@ Override

Public FileVisitResult visitFile (Path file, BasicFileAttributes attrs) throws IOException {

BasicFileAttributes attributes = Files. readAttributes (file, BasicFileAttributes. class );

System. out. println ("visitFile path =" + file + "\ tisDirectory =" + attributes. isDirectory ()

+ "\ Tsize =" + attributes. size ());

Return FileVisitResult. CONTINUE;

}

@ Override

Public FileVisitResult visitFileFailed (Path file, IOException exc) throws IOException {

System. out. println ("visitFileFailed path =" + file );

Return FileVisitResult. CONTINUE;

}

@ Override

Public FileVisitResult postVisitDirectory (Path dir, IOException exc) throws IOException {

System. out. println ("preVisitDirectory path =" + dir );

Return FileVisitResult. CONTINUE;

}

});

  • ZIP file system

    The Paths class searches for the path in the default file system, that is, the file on the user's local disk, or in another file system, such as the ZIP file system. Example code:

    Path zipPath = Paths. get ("C: \ Users \ Downloads", "commons-logging-1.2-bin.zip ");

    FileSystem fs = FileSystems. newFileSystem (zipPath, null );

    A file system will be created, including all the files in the ZIP file. If you know the file name, you can reproduce the entire file from the ZIP file. The sample code is as follows:

    Files. copy (fs. getPath ("commons-logging-1.2 \ LICENSE.txt"), Paths. get ("d: \ LICENSE.txt "));

    Among them, fs. getPath is similar to Paths. get for any file system. If you want to traverse all the files in the ZIP file, you can also use the partial filetree method for processing. Example code:

    Files. Program filetree (fs. getPath ("/"), new SimpleFileVisitor <Path> (){

    Public FileVisitResult visitFile (Path file, BasicFileAttributes attrs ){

    System. out. println ("Zip File" + file );

    Return FileVisitResult. CONTINUE;

    }

    });

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.