标签:
A file‘s status is 3-valued:
So !Files.exists(path) != Files.notExists(path).
If both exists and notExists return false, the existence of the file cannot be verified.
To verify a program can access a file as needed, use isReadable(path), isWritable(path), isExecutable(path) methods.
1 Path = … 2 boolean isRegularExecutableFile = File.isRegularFile(file) & Files.isReadable(file) & Files.isExecutable(file);
When symbolic paths exists, 2 paths maybe direct to same file, use isSameFile(p1,p2) to compare.
1 Path p1 = ...; 2 Path p2 = ...; 3 if (Files.isSameFile(p1,p2)){ 4 //Code when 2 paths locate the same file 5 }
Delete a file/dir: deleteIfExists(path)
1 try{ 2 Files.delete(path); 3 }catch(NoSuchFileException x){ 4 System.err.format("%s: no such " + "file or dir%n", path); 5 }catch(DirectoryNotEmptyException x){ 6 System.err.format("%s not empty%n",path); 7 }catch(IOException x){ 8 //File permissions problems are caught here. 9 System.err.println(x); 10 }
Copy a file/dir: Copy files may fail when target file exists, unless the REPLACE_EXISTING option is spec. Directory can be copied, but not with files inside it. When copy a symbolic link, the target of the link is copied, not the link. And if need to copy the link, spec. either NOFOLLOW_LINKS or REPLACE_EXISTING option. This method takes a varargs argument. 3 options are supported:
1 //import static methods from package 2 import static java.nio.file.StandardCopyOption.*; 3 ... 4 Files.copy(src,dest,Options...);
in addition to file copy, copy method can also be used to copy between file & stream. Usage: copy(InputStream, Path, Options...) & copy(Path, OutputStream).
See this method to support copy recursively.
Move a file/dir: move(path, path, option...) fails if target exists, unless REPLACE_EXISTING spec. Empty dir can be moved, on UNIX systems, moving a dir is equaling to renaming a dir, in that circumstances, non-empty dir can be moved, too. Options:
1 //import static methods from package 2 import static java.nio.file.StandardCopyOption.*; 3 ... 4 File.move(src,dest,REPLACE_EXISTING);
Metadata: what is metadata? "Data about other data". In OS, data is contained in files/dirs, so the metadata tracks info about each of the objects: is it a regular file, a dir or a link? Size, cdate, lmdate, owner, accpermissions?
readAttributes(path, String, Option); readAttributes(path, Class<A>, Option);
1 //using the BasicFileAttributes class to retrive file attributes 2 Path file = ...; 3 BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class); 4 System.out.println(attr.creationTime() + attr.lastAccessTime() + 5 attr.lastModifiedTime() + attr.isDirectory() + attr.isOther() + 6 attr.isRegularFile() + attr.isSymbolicLink() + attr.size());
Set the FileTime:
1 Path file = ...; 2 BasicFileAttributes attr = 3 Files.readAttributes(file, BasicFileAttributes.class); 4 long currentTime = System.currentTimeMillis(); 5 FileTime ft = FileTime.fromMillis(currentTime); 6 Files.setLastModifiedTime(file, ft);
Create Dirs:
1 //createDirectory(path, FileAttribute<?>) 2 Path dir = ...; 3 Files.createDirectory(dir); 4 //way to set permission 5 Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---"); 6 FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); 7 Files.createDirectory(file, attr);
List all root dirs of filesystem:
1 Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories(); 2 for (Path name:dirs){ 3 System.err.println(name); 4 }
List contents in Dir:
Usage: newDirectoryStream(path), return an object that implements DirectoryStream interface, this interface implements Iterable, so iterate through the directory stream, behaves well even in large directories.
1 Path dir = ...; 2 try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)){ 3 for(Path file:stream){ 4 System.out.println(file.getFileName); 5 } 6 }catch(IOException | DirectoryIteratorException x){ 7 //IOException can never be thrown by this iteration. 8 //In this snippet, it can only be thrown by newDirectoryStream. 9 System.out.println(x); 10 }
1 //file filter 2 DirectoryStream<Path> stream = Files.newDirectoryStream(dir, *.{java,jar}); 3 4 //using DirectoryStream.Filter<T>, rewrite accept(), anonyinter class 5 DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>(){ 6 Public boolean accept(Path file) throws IOException{ 7 try{ 8 return (Files.isDirectory(file); 9 }catch (IOException x){ 10 //Failed to determine it‘s a directory 11 System.err.println(x); 12 return false; 13 } 14 } 15 }; 16 17 DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter);
Path Class & File Class conversion:
1 Path path = Paths.get("1.txt"); 2 //Convert a Path obj to File obj 3 File file = path.toFile(); 4 file.getCanonicalFilePath(); 5 //Convert a File obj to Path obj 6 path = file.toPath(); 7 path.getFileName();
About Links & Symbolics:
Basic steps to implement a watch service:
1 //use the newWatchService() method in FileSystem class 2 WatchService watcher = FileSystems.getDefault().newWatchService(); 3 //Any obj implements Watchable interface can be registered, include Path class 4 //Path class implements 2 register methods, choose one, the other takes a 5 //WatchEvent.Modifier. Choose the types to be monitored, supported 6 //StandardWatchEventKinds: 7 //ENTRY_CREATE 8 //ENTRY_DELETE 9 //ENTRY_MODIFY 10 //OVERFLOW - indicate the event have been lost or discarded, do not have to indicate this identifier to receive it. 11 //register a path instance for all three types: 12 import static java.nio.file.StandardWatchEventKinds.*; 13 14 Path dir = ...; 15 try{ 16 WatchKey key = dir.register(watcher, 17 ENTRY_CREATE, 18 ENTRY_MODIFY, 19 ENTRY_DELETE); 20 }catch (IOException x){ 21 System.err.println(x); 22 }
Usage of WatchService API:
1 for (;;) { 2 3 // wait for key to be signaled 4 WatchKey key; 5 try { 6 key = watcher.take(); 7 } catch (InterruptedException x) { 8 return; 9 } 10 11 for (WatchEvent<?> event: key.pollEvents()) { 12 WatchEvent.Kind<?> kind = event.kind(); 13 14 // This key is registered only 15 // for ENTRY_CREATE events, 16 // but an OVERFLOW event can 17 // occur regardless if events 18 // are lost or discarded. 19 if (kind == OVERFLOW) { 20 continue; 21 } 22 23 // The filename is the 24 // context of the event. 25 WatchEvent<Path> ev = (WatchEvent<Path>)event; 26 Path filename = ev.context(); 27 28 // Verify that the new 29 // file is a text file. 30 try { 31 // Resolve the filename against the directory. 32 // If the filename is "test" and the directory is "foo", 33 // the resolved name is "foo/test". 34 Path child = dir.resolve(filename); 35 if (!Files.probeContentType(child).equals("text/plain")) { 36 System.err.format("New file ‘%s‘" + 37 " is not a plain text file.%n", filename); 38 continue; 39 } 40 } catch (IOException x) { 41 System.err.println(x); 42 continue; 43 } 44 45 // Email the file to the 46 // specified email alias. 47 System.out.format("Emailing file %s%n", filename); 48 //Details left to reader.... 49 } 50 51 // Reset the key -- this step is critical if you want to 52 // receive further watch events. If the key is no longer valid, 53 // the directory is inaccessible so exit the loop. 54 boolean valid = key.reset(); 55 if (!valid) { 56 break; 57 } 58 }
How to suppress warning of known safe operations?
1 //Create a method that do the operation and suppress certain type of warning 2 @SuppressWarnings("unchecked") 3 static <T> WatchEvent<T> cast(WatchEvent<?> event){ 4 return (WatchEvent<Path>)event; 5 }
Always ok to use this API WatchService, if filesystem support file change notif, API takes advantage of it, if do not support, API will poll the filesystem itself, waiting for changes.
The Files.probeContentType determined by the platform‘s default file type detector. In windows, the detector might determine a file content to be application/x-java based on the .class extension. That may go wrong. So if needed, custom a FileTypeDetector.
Default File System: use FileSystems.getDefault() to retrieve the default file system.
Path String Separator: To get the default file path separator of file system, use FileSystems.getDefault().getSeparator() or File.separator.
File Stores/Root Dirs: use FileSystems.getDefault().getFileStores(), FileSystems.getDefault().getRootDirectories(), Iterable<FileStore>|Iterable<Path>. return a file‘s root by: Files.getFileStore(path) | path.getRoot()
java.nio.file package:
标签:
原文地址:http://www.cnblogs.com/sansna/p/5390227.html