Portable file operations - Files
Separator
-
In Windows system, backslash '' or slash '/' is used as the separator of the path. However, when using backslash, it needs to be noted that a single backslash represents the escape character, so when using backslash as the separator of the path, it needs to appear in pairs
File file1 = new File("E:\\aaa\\1.java"); File file2 = new File("E:/aaa/1.java");
-
In Linux, Unix, Mac OS, use slash '/' as the separator of path
-
You can use the File.separator provided by the File class, and the program will match the separator corresponding to the system according to the current system
File file3 = new File("D:" + File.separator + "aaaa" + File.separator + "1.java");
Path
Summary
Path represents a sequence of directory names followed by a file name. The first part of the path can be a root, such as / or C: \, and the path starting at the root is an absolute path, otherwise it is a relative path. for instance:
Path path = Paths.get("/home", "path", "demo"); path = /home/path/demo Path path1 = Paths.get("home", "path", "demo"); path1 = home/path/demo
Path API
//Combined path. If the other is an absolute path, return the other; otherwise, return the path obtained by connecting this and the other Path resolve(String other); Path resolve(Path other); //Combined path. If the other is an absolute path, return the other; otherwise, return the path obtained by connecting the parent path of this and the other Path resolveSibling(String other); Path resolveSibling(Path other); //Return relative path relative to other Path relativize(other); //Remove redundant path elements such as. And Path normalize(); //Return to absolute path Path toAbsolutePath(); //Return the parent path, or null if not Path getParent(); //Return the last path part of the path Path getFileName(); //Return the following path of the file Path getRoot(); //Create File objects from this path Path toFile();
Files
Summary
The Files utility class can make normal file operations fast. For example:
//Read all contents of the file byte[] bytes = Files.readAllBytes(path); //Read by line List<String> lines = Files.readAllLines(path); List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); //File out Path write = Files.write(path, bytes); Path write = Files.write(path, lines);
These simple methods are suitable for processing medium length files. If you want to process large length files or binary files, you should still use input / output stream or reader / writer:
InputStream in = Files.newInputStream(path); OutputStream out = Files.newOutputStream(path); BufferedReader in = Files.newBufferedReader(path); BufferedWriter out = Files.newBufferedWriter(path);
Create files and directories
//Create directory Path directory = Files.createDirectory(path); //Create directory recursively Path directory1 = Files.createDirectories(other); //create a file Path file = Files.createFile(filePath); //Create temporary file directory Path tempFile = Files.createTempFile(path, "demoTemp", ".text"); //The new file is path/demoTemp1755677485909684463.text Path tempFile1 = Files.createTempFile("demoTemp", ".text"); //New file is: / var /.. / demotemp7347118361156223079.text Path tempFile2 = Files.createTempFile(null, ".text"); //New file is / var/.../6300881984327212300.text Path tempDirectory = Files.createTempDirectory(path, "demoTemp"); //The new directory is: path/demoTemp201107870961044007 Path tempDirectory1 = Files.createTempDirectory("demoTemp"); //The new directory is: / var /.. / demotemp4584110971885510312
Copy, move, and delete files
/** * fromPath:/path/from/demo.text * toPath:/path/to/demo.text */ //Copy file Path copy = Files.copy(fromPath, toPath); //Store the input stream on the hard disk long copy2 = Files.copy(inputStream, toPath); //Copy Path to output stream long copy1 = Files.copy(fromPath, outputStream); //move file Path move = Files.move(fromPath, toPath); //Delete file, throw exception if file does not exist Files.delete(toPath); //Delete files or remove empty directories boolean exists = Files.deleteIfExists(toPath);
When copying files, if the destination path already exists, the copy or move will fail. If you want to overwrite the existing target path, you can use the replace? Existing option. If you want to copy all the ATTRIBUTES of a file, you can use the ATTRIBUTES option. You can use the atomic? Move option to guarantee the atomicity of the move
Path move = Files.move(fromPath, toPath, StandardCopyOption.ATOMIC_MOVE);
Access items in the directory
The static Files.list method returns a Stream object that can read items in the directory. Directories are read lazily, which makes it more efficient to work with directories with a large number of projects.
All subdirectories can be obtained recursively by using the Files.walk method. Using the walk method to delete a tree is difficult because you need to delete the subdirectory before deleting the parent directory
Because reading a directory involves shutting down system resources, you should use the try block:
try(Stream<Path> entries = Files.list(path)){ ... }
Example: copying one directory to another
Path target = Paths.get(""); Files.walk(path).forEach(p -> { try { Path q = target.resolve(p); if (Files.isDirectory(p)) { Files.createDirectory(q); } else { Files.copy(p, q); } } catch (IOException e) { e.printStackTrace(); } });
Use directory stream
Using a directory stream to delete a directory tree
Path root = Paths.get(""); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e != null) { throw e; } Files.delete(dir); return FileVisitResult.CONTINUE; } });
appendix
Files API
//Create a file or directory static Path createDirectory(Path dir, FileAttribute<?>... attrs) static Path createDirectories(Path dir, FileAttribute<?>... attrs) static Path createFile(Path path, FileAttribute<?>... attrs) //Create a temporary file or directory in the appropriate location or given parent directory, and return the path to create the file or directory static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) //Copy or move from to a specific location and return to static Path copy(Path source, Path target, CopyOption... options); static Path move(Path source, Path target, CopyOption... options); //Copy from input stream to file or from file to output stream static long copy(Path source, OutputStream out); static long copy(InputStream in, Path target, CopyOption... options); //Delete file or empty directory static void delete(Path path); static boolean deleteIfExists(Path path); //The first will throw an exception when the file or directory does not exist, and the second will directly return false //Get file information static boolean exists(Path path, LinkOption... options); static boolean isHidden(Path path, LinkOption... options); static boolean isReadable(Path path); static boolean isWritable(Path path); static boolean isExecutable(Path path); static boolean isRegularFile(Path path, LinkOption... options); static boolean isDirectory(Path path, LinkOption... options); static boolean isSymbolicLink(Path path); //Get bytes of file static long size(Path path); //Read file properties of type A static <A extends BasicFileAttributes> A readAttributes(Path path,Class<A> type,LinkOption... options); //Get the file or directory in the directory static DirectoryStream<Path> newDirectoryStream(Path dir); static DirectoryStream<Path> newDirectoryStream(Path dir, String glob); //Traverse all descendants static Path walkFileTree(Path start, FileVisitor<? super Path> visitor)
Standard options for file operations
-
StandardOpenOption
option describe READ Open for read WRITE Open for writing APPEND Append at the end of the file when writing TRUNCATE_EXISTING Remove existing contents of file on write CREATE Automatically create files when they don't exist CREATE_NEW Failed to create file if it exists DELETE_ON_CLOSE Delete the file as "possible" when it is closed SPARSE Give the file system a hint that the file is sparse SYNC Every update of data and metadata must be synchronously written to the storage device DSYNC Every update of file data must be synchronously written to the storage device -
StandardCopyOption
option describe REPLACE_EXISTING Replace the target if it already exists COPY_ATTRIBUTES Copy all properties of a file ATOMIC_MOVE Atomic mobile file -
LinkOption
option describe NOFOLLOW_LINKS Do not follow symbolic links -
FileVisitOption
option describe FOLLOW_LINKS Trace symbolic links
Glob mode
Pattern | describe | Example |
---|---|---|
* | Matches 0 or more characters (excluding subdirectories) in the path component | *.java |
** | Match 0 or more characters (including subdirectories) across directory boundaries | **.java |
? | Match a character | demo?.java |
[...] | Match a character set ([0-9], [A-F], [! 0-9]) | demo[0-9].java |
{...} | Match one of multiple options separated by commas | *.{java, class} |
\ | Translate characters in any of the above modes and \ characters |