Java 7 introduced nio.2,nio.2 as a framework that inherits from NIO and adds new functionality (for example, the ability to handle soft links and hard links). This post consists of three sections, and I'll use some examples of nio.2 to show you the basic use of nio.2.
Next Address http://blog.csdn.net/u011225629/article/details/46386599
File copy
Q: How do I copy a file?
A: You can use the Java.nio.file.Files class's public static path copy (path source, path target, copyoption ... options) method to implement this function, This method can be used to copy from the source file to the target file.
By default, if the destination file already exists or is a symbolic link, the copy fails. However, if the source and destination files are the same file, the copy action will not be executed.
In addition, there are some things to note:
- A copy of the properties of the file is not required.
- If a symbolic link is supported, the copy is a link to the final destination file when the source file is a symbolic link.
- When the source file is a directory, the copy () method generates an empty directory for the target location (elements in the directory are not copied).
The behavior of the method is changed after each parameter of the Java.nio.file.CopyOption type is passed to the variable argument list of the copy () method. This parameter is a java.nio.file.StandardCopyOption type or Java.nio.file.LinkOption enumeration constant:
- Copy_attributes: Attempt to copy the properties of the file to the destination file. These properties depend on the platform and the file system and are therefore indeterminate. However, at a minimum, if the storage of both the source and destination files supports the last modified time attribute, the property is copied to the destination file. However, when you need to be aware, the accuracy of the timestamp of the copied file may be lost.
- Nofollow_links: A different symbolic link. If the file is a symbolic link, the copy is the symbolic link itself instead of the target file it references. Its special implementation is whether to copy the properties of the file to the new link, in other words, when copying a symbolic link, copy_attributes may be ignored.
- Replace_existing: When the destination file already exists, the target file will be replaced unless the destination file is a non-empty directory. When the target file is a symbolic link and already exists, only the symbolic link itself is replaced without changing the file referenced by the symbolic link.
The copy () method does not support the Atomic_move option for Standardcopyoption, which is a meaningless option in a file copy. I will describe the Atomic_move option later in the discussion about file movement.
Non-atomic copies:
Copying a file is a non-atomic operation. If the java.io.IOException exception is thrown, it means that the target file may not have been copied or the properties of the file have not been copied from the source file. If the replace_existing mode is specified and the destination file already exists, the destination file is already replaced. In addition, checks for the existence of files that already exist on the file system and the creation of new files may not be atomic.
In addition to Java.lang.securityexception,copy (), one of the following exceptions is thrown:
- Java.nio.file.DirectoryNotEmptyException:REPLACE_EXISTING mode, the destination file cannot be replaced because it is a non-empty directory file.
- Java.nio.file.FileAlreadyExistsException: The destination file already exists, but the replace_existing parameter is not specified and cannot be replaced.
- IOEXCEPTION:I/O exception
- Java.lang.UnsupportedOperationException: The incoming mutable parameter copyoptions is not supported.
Specific exceptions that are optional:
Directorynotemptyexception and filealreadyexistsexception are optional exceptions, and they are optional because these exceptions are thrown by the underlying operating system to be recognized, if not recognized, Throw IOException to replace it.
I have created a small application to show the most basic methods of the copy () method. Listing 1 shows the source code for the application:
List 1:copy.java
Import Java.io.ioexception;import Java.nio.file.directorynotemptyexception;import Java.nio.file.files;import Java.nio.file.filealreadyexistsexception;import Java.nio.file.path;import Java.nio.file.paths;public class Copy{ Public static void Main (string[] args) { if (args.length! = 2) { System.err.println ("Usage:java Copy source Target"); return; } Path Source = Paths.get (Args[0]); Path target = Paths.get (args[1]); Try { files.copy (source, target); } catch (filealreadyexistsexception Faee) { System.err.printf ("%s:file already exists%n", target); } catch (directorynotemptyexception Dnee) { System.err.printf ("%s:not empty%n", target); } catch (IOException IoE) { System.err.printf ("I/O error:%s%n", Ioe.getmessage ());} }}
The main () method of Listing 1 first verifies that the command line confirms that there are two parameters that represent the source and destination files, and if not, outputs relevant information and ends the program.
Next, the static method of the Java.nio.file.Paths class is called two times by the path get (Uri Uri) method, and the Java.nio.file.Path instance object of the source and destination files is obtained from the file system by file name.
The Path object is now uploaded to the copy () method. If the method executes successfully, no information will be output, otherwise the appropriate error message will be output.
Compile the code in Listing 1 (Javac Copy.java) and run the program. For example, execute Java copy Copy.java Copy.bak. You can try to copy a non-empty directory to another directory. What happens?
As an exercise, you can modify Copy.java to add command-line arguments that enable the program to recognize Copyoptions, then pass in the corresponding enumeration constants to the copy () method, and then observe the effects of these parameters on the copy () function.
Backwards compatible
To be compatible with the past stream-based I/O framework, the files class provides variants of the following two copy () methods:
public static long copy (InputStream in, Path target, copyoption ... options)
public static long copy (Path source, outputstream out)
Later in this series, I will demonstrate the copy method in the extension list 1 so that this method can copy a directory and subdirectories into another directory.
Delete Files and directories
Q: How do I delete a file or directory?
A: You can use the public static void Delete (path path) method of the files class to delete a file or directory that is deleted based on the path to the file or directory:
- If the file referenced by the path is an open file that is being used, some operating systems will prevent the file from being deleted.
- If the path refers to a directory, the directory must be empty (unless it is a special file for a special operating system).
- If the path refers to a symbolic link, the method removes only the symbolic link and does not delete the file to which the symbolic link points.
Non-atomic deletion
The implementation of the method is likely to require checking whether the physical file is in the current directory. For this reason, the delete () method may not be atomic for some operating systems. For portability and security reasons, you should not assume that the implementation of the Delete () method is atomic.
Delete () throws IOException when an I/O exception is encountered, if the file to be deleted does not exist, Java.nio.file.NoSuchFileException will be thrown, and if the directory is not empty, directorynotemptyexception will be thrown.
Specific exceptions that are optional:
Nosuchfileexception is an optional, specific exception.
I created a small application that demonstrates how to use the Delete () method. The source code for the application is listed in Listing 2.
List 2:delete.java
Import Java.io.ioexception;import Java.nio.file.directorynotemptyexception;import Java.nio.file.files;import Java.nio.file.nosuchfileexception;import Java.nio.file.path;import Java.nio.file.paths;public class Delete{ public static void Main (string[] args) { if (args.length! = 1) { System.err.println ("Usage:java Delete File-or-directory "); return; } Path Path = Paths.get (Args[0]); Try { files.delete (path); } catch (nosuchfileexception nsfe) { System.err.printf ("%s:no such file or directory%n", path); } catch (directorynotemptyexception Dnee) { System.err.printf ("%s:not empty%n", path); } catch (IOException IoE) { System.err.printf ("I/O error:%s%n", Ioe.getmessage ());} }}
The main () method of Listing 2 first validates the command-line arguments, ensuring that only one parameter is passed in, which is the path to a file or directory. If not, it will output useful information and end the program.
Next, call the Get () method of the paths class to get the Path object, which represents the file or directory in the file system.
The path object is now passed into the Delete () method. If the method executes successfully, no information will be output. However, if it fails, the appropriate error message is output.
Compile the code in List 2 (Javac Delete.java) and run the application. Try to delete a read-write file, a read-only file, a non-empty directory, and a symbolic link, and then observe the result of the deletion.
Deleteifexists Method:
The files class declares a static method, Boolean deleteifexists (path Path), as a variant of delete (). The only difference between the two methods is that deleteifexists only deletes the existing file, so the Deleteifexists method never throws a Nosuchfileexception exception.
To move a file:
Q: How do I move a file?
A: You can use the files class's public static path Move (path source, path target, copyoption ... options) method to move the file, The function of this method is to move from the source file to the target file.
By default, this method attempts to move the source file to the destination file, and an exception occurs when the destination file already exists, unless the destination file is the source file itself, in which case the method does not work.
The behavior of the method is changed after each parameter of the Copyoption type is passed to the variable argument list of the move () method. The parameter is an enumeration constant of type java.nio.file.StandardCopyOption:
- The Atomic_move:move method behaves as an atomic file system operation, and all other parameters are ignored. When the target file already exists, the specific implementation shows whether the existing file can be replaced or an IO exception will be thrown. If the Move method does not implement atomic file system operations, an Java.nio.file.AtomicMoveNotSupportedException exception will be thrown.
- Replace_existing: When the target file already exists, the target file will be replaced unless the target file is a non-empty directory. When the destination file already exists and is a symbolic link, only the symbolic link itself is replaced, not the file that the symbolic link points to.
In addition to Atomicmovenotsupportedexception, the Move method throws an exception that is consistent with the copy method.
I created a small application to demonstrate the most basic use of the Move method. Listing 3 lists the source code for the application, which is basically consistent with the code in Listing 1.
List 3:move.java
Import Java.io.ioexception;import Java.nio.file.directorynotemptyexception;import java.nio.file.files;import Java.nio.file.filealreadyexistsexception;import Java.nio.file.path;import Java.nio.file.paths;public class Move{ public static void Main (string[] args) {if (args.length! = 2) {System.err.println ("Usage:java Move SOURCE Target "); Return } Path Source = Paths.get (Args[0]); Path target = Paths.get (args[1]); try {files.move (source, target); } catch (Filealreadyexistsexception Faee) {System.err.printf ("%s:file already exists%n", target); } catch (Directorynotemptyexception Dnee) {System.err.printf ("%s:not empty%n", target); } catch (IOException IoE) {System.err.printf ("I/O error:%s%n", Ioe.getmessage ()); } }}
Compile listing 3 and run the application. For example, suppose you have a file named Report.txt that executes Java Move report.txt report bak. What happens when you move a file to another file that already exists?
As an exercise, you can modify Move.java to add command-line arguments that enable the program to recognize Copyoptions, then pass in the corresponding enumeration constants to the Move () method, and then observe the effects of these parameters on the move () function.
What's next
In the second part, I will demonstrate path-related methods (such as getting paths, retrieving path information), file or directory test methods (such as the existence of a test file or directory), and some methods for attributes.
This paper draws on http://www.codeceo.com/article/nio-2-guide-1.html
Crazy Java Learning Note (nio.2)-----------first article