10-java nio之【注意事项】

10.1 Refactoring java.io.File code

java.io.File vs java.nio.file

Javadoc Description | java.io.File | java.nio.File --|--|-- Class name| java.io.File| java.nio.file.Path Tests this abstract pathname for equality with the given object | File.equals(Object) | Path.equals(Object) Compares two abstract pathnames lexicographically |File.compareTo(File) |Path.compareTo(Path) Returns the absolute pathname string of this abstract pathname |File.getAbsolutePath() |Path.toAbsolutePath() Returns the absolute form of this abstract pathname |File.getAbsoluteFile()| Path.toAbsolutePath() Returns the canonical pathname string of this abstract pathname |File.getCanonicalPath()| Path.toRealPath(LinkOption...) Path.normalize() Returns the canonical form of this abstract pathname | File.getCanonicalFile() | Path.toRealPath(LinkOption...) Path.normalize() Constructs a file: URI that represents this abstract pathname | File.toURI() | Path.toUri() Tests whether the file denoted by this abstract pathname is a normal file | File.isFile()| Files.isRegularFile(Path, LinkOption ...) Tests whether the file denoted by this abstract pathname is a directory| File.isDirectory()| Files.isDirectory(Path, LinkOption...) Tests whether the file named by this abstract pathname is a hidden file |File.isHidden() | Files.isHidden(Path) Tests whether the application can read the file denoted by this abstract pathname| File.canRead() | Files.isReadable(Path) Tests whether the application can modify the file denoted by this abstract pathname| File.canWrite()| Files.isWritable(Path) Tests whether the application can execute the file denoted by this abstract pathname| File.canExecute() | Files.isExecutable(Path) Tests whether the file or directory denoted by this abstract pathname exists| File.exists()| Files.exists(Path, LinkOption ...) Files.notExists(Path,LinkOption ...) Creates the directory named by this abstract pathname | File.mkdir()| Files.createDirectory(Path, FileAttribute<?> ...) Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories| File.mkdirs()| Files.createDirectories(Path, FileAttribute<?> ...) 创建不存在的文件| File.createNewFile()| Files.createFile(Path, FileAttribute<?> ...) Returns an array of strings naming the files and directories in the directory, denoted by this abstract pathname | File.list() File.listFiles() | Files.newDirectoryStream(Path) Returns an array of strings naming the files and directories in the directory, denoted by this abstract pathname that satisfy the specified filter | File.list(FilenameFilter) File.listFiles(FileFilter) File.listFiles(FilenameFilter)| Files.newDirectoryStream(Path, DirectoryStream.Filter<? super Path>) Files.newDirectoryStream(Path,String) The length of the file denoted by this abstract pathname | File.length() | Files.size(Path) Deletes the file or directory denoted by this abstract pathname| File.delete()| Files.delete(Path) Files.deleteIfExists(Path) Renames the file denoted by this abstract pathname |File.renameTo(File)| Files.move(Path, Path, CopyOption) Sets the owner or everybody’s execute permission for this abstract pathname | File.setExecutable(boolean,boolean) | Files.setAttribute(Path, String, Object, LinkOption...) Sets the owner or everybody’s read permission for this abstract pathname | File.setReadable(boolean,boolean) | Files.setAttribute(Path, String, Object, LinkOption...) Marks the file or directory named by this abstract pathname so that only read operations are allowed | File.setReadOnly() | Files.setAttribute(Path, String, Object, LinkOption...) Sets the owner or everybody’s write permission for this abstract pathname |File.setWritable(boolean, boolean) | Files.setAttribute(Path, String, Object, LinkOption...) Returns the time that the file denoted by this abstract pathname was last modified | File.lastModified() |Files.getLastModifiedTime(Path path, LinkOption... options) Sets the last-modified time of the file or directory named by this abstract pathname | File.setLastModified(long) | Files.setLastModifiedTime(Path, FileTime) Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name | File.createTempFile(String, String) | Files.createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name | File.createTempFile(String, String, File) | Files.createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) Returns the size of the partition named by this abstract pathname| File.getTotalSpace() | FileStore.getTotalSpace() Returns the number of unallocated bytes in the partition named by this abstract path name | File.getFreeSpace() | FileStore.getUnallocatedSpace()| Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname| File.getUsableSpace()| FilesStore.getUsableSpace() Lists the available file system roots | File.listRoots() | FileSystem.getRootDirectories() Random access file | java.io.RandomAccessFile| java.nio.channels.SeekableByteChannel Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates |File.deleteOnExit()| Replaced by the DELETE_ON_CLOSE option Combines two paths| new File(parent,"new_file") | parent.resolve("new_file")

10.2 Working with the ZIP file system provider

First, we create a simple HashMap that contains the configurable properties of a ZIP file system created by the ZFSP. Currently, there are two properties that can be configured:

  • create: The value can be true or false, but of type java.lang.String. If the value is true, the ZFSP creates a new ZIP file if it does not exist.
  • encoding: The value is a java.lang.String indicating the encoding scheme (e.g., UTF-8, US-ASCII, ISO-8859-1, etc.). UTF-8 is the default.

Therefore, we can indicate that the ZIP file exists and the needed encoding is ISO-8859-1 like so:

Map<String, String> env = new HashMap<>();
env.put("create", "false");
env.put("encoding", "ISO-8859-1");

URI uri = URI.create("jar:file:/C:/rafaelnadal/tournaments/2009/Tickets.zip");
FileSystem ZipFS = FileSystems.newFileSystem(uri, env);
public static FileSystem newFileSystem(Path path, ClassLoader loader) throws IOException
public static FileSystem newFileSystem(URI uri, Map<String,?> env, ClassLoader loader) throws IOException
package com.eshore.aio;

import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;

/**
* Created by ad on 2015/3/25.
*/
public class ZipSystemProviderTest {
      public static void main(String[] args) throws IOException {
            //set zip file system properties
            Map<String, String> env = new HashMap<>();
            env.put("create", "false");
            env.put("encoding", "ISO-8859-1");

            //locate file system with java.net.JarURLConnection
            URI uri = URI.create("jar:file:/C:/rafaelnadal/tournaments/2009/Tickets.zip");
            try (FileSystem ZipFS = FileSystems.newFileSystem(uri, env)) {
                  Path fileInZip = ZipFS.getPath("/AEGONTickets.png");
                  Path fileOutZip = Paths.get("C:/rafaelnadal/tournaments/2009/AEGONTicketsCopy.png");

                  //copy AEGONTickets.png outside the archive
                  Files.copy(fileInZip, fileOutZip);
                  System.out.println("The file was successfully copied!");
            }
      }
}

10.3 Considerations about custom file system providers

Creating a Custom File System Provider

  1. Extend the java.nio.file.spi.FileSystemProvider class.
  2. Define a URI scheme for the provider (the getScheme() method should return this URI scheme).
  3. Create an internal cache for managing the provider’s created file systems.
  4. Implement the newFileSystem() and getFileSystem() methods for creating a file system and for retrieving a reference to an existing file system.
  5. Implement the newFileChannel() or the newAsyncronousFileChannel() method, which returns a FileChannel object that allows a file to be read or written in the file system.

Creating a Custom File System

  1. Extend the java.nio.file.FileSystem class.
  2. Implement the methods of the file system according to your needs (you may need to define the number of roots, read/write access, file stores, etc.).

For more details, you may want to take a closer look at official documentation, at http://download.oracle.com/javase/7/docs/technotes/guides/io/fsp/filesystemprovider.html.

10.4 Useful Methods

  • Default File System

You’ve seen how to get the default file system many times in this book, but we’re putting this so you can easily access this information if you forget. Getting the default file system is accomplished through the FileSystems.getDefault() method:

FileSystem fs = FileSystems.getDefault();
  • File Stores

Getting the file system file stores is another well-covered subject in the book, but for a quick reminder, come here. Here’s the required code:

for (FileStore store: FileSystems.getDefault().getFileStores()) {
     ...
}
  • Path of a File

Here’s how to get the path of a file:

Path path = Paths.get("...");
Path path = FileSystems.getDefault().getPath("...");
Path path = Paths.get(URI.create("file:///..."));
Path path = Paths.get(System.getProperty("user.home"), "...");

Path String Separator
As you know, a path string separator is OS dependent. To retrieve the Path string separator for the default file system, you can use one of the following approaches:

String separator = File.separator;
String separator = FileSystems.getDefault().getSeparator();

猜你喜欢

转载自my.oschina.net/funcy/blog/1821528