博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java NIO Related
阅读量:5874 次
发布时间:2019-06-19

本文共 11223 字,大约阅读时间需要 37 分钟。

A file's status is 3-valued:

  1. The file is verified to exist;
  2. The file is verified to not exist;
  3. The file's status is unknown, when program has not sufficient right to the file.

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. REPLACE_EXISTING: if dir not empty, copy fails with FileAlreadyExistsException
  2. COPY_ATTRIBUTES: attributes are OS-spec. however, last-modified-time is across platform supported
  3. NOFOLLOW_LINKS
1 //import static methods from package2 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  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. REPLACE_EXISTING: if target is symbolic link, the target is replaced without affecting the link it points to
  2. ATOMIC_MOVE: move as an atomic file operation, if OS does not support atomic move, throw exception. This option guarantees that any other process watching the directory the file will be moved to should access and get a complete file.
1 //import static methods from package2 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 attributes2 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 permission5 Set
perms = PosixFilePermissions.fromString("rwxr-x---");6 FileAttribute
> attr = PosixFilePermissions.asFileAttribute(perms);7 Files.createDirectory(file, attr);

List all root dirs of filesystem:

1 Iterable
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
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
stream = Files.newDirectoryStream(dir, *.{java,jar}); 3 4 //using DirectoryStream.Filter
, rewrite accept(), anonyinter class 5 DirectoryStream.Filter
filter = new DirectoryStream.Filter
(){ 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 directory11 System.err.println(x);12 return false;13 }14 }15 };16 17 DirectoryStream
stream = Files.newDirectoryStream(dir, filter);

Path Class & File Class conversion:

1 Path path = Paths.get("1.txt");2 //Convert a Path obj to File obj3 File file = path.toFile();4 file.getCanonicalFilePath();5 //Convert a File obj to Path obj6 path = file.toPath();7 path.getFileName();

About Links & Symbolics:

  1. Symbolics: createSymbolicLink(link, target, attr);
  2. Hard Link: createLink(link, target);
  3. Use Files.isSymbolicLink(file) static method to determine. boolean
  4. Use Files.readSymbolicLink(link) to find the target of link, return type Path, if not a symbolic link, throws a NotLinkException

Basic steps to implement a watch service:

  1. Create a WatchService "watcher" for file system
  2. For each directory need monitoring, register with watcher, spec. the type of events wanted, receive a WatchKey instance for each dir registered
  3. implement an infinite loop to wait for incoming events, if triggered, key is signaled & placed into the watcher's queue
  4. Retrieve the key from queue, obtain the file name wanted from key
  5. Retrieve each pending event for the key (there might be multiple events) & process
  6. reset key, resume waiting
  7. Close service if no long needed by exit the thread or when it's .closed()
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_MODIFY10 //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:

  • watcher.poll()
  • watcher.poll(long,TimeUnit)
  • watcher.take()
  • key.pollEvents(): fetch a list of WatchEvents(StandardWatchEventKinds)
  • (WatchEvent<?> event.kind()): get exactly the kind type, can be compared
  • (WatchEvent<Path> event).context(): return the filename related to signal
  • key.reset(): exit loop if this method returns false, prepare the key to be signaled again
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 only15 // for ENTRY_CREATE events,16 // but an OVERFLOW event can17 // occur regardless if events18 // are lost or discarded.19 if (kind == OVERFLOW) {20 continue;21 }22 23 // The filename is the24 // context of the event.25 WatchEvent
ev = (WatchEvent
)event;26 Path filename = ev.context();27 28 // Verify that the new29 // 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 the46 // 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 to52 // 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 warning2 @SuppressWarnings("unchecked")3 static 
WatchEvent
cast(WatchEvent
event){4 return (WatchEvent
)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:

  • Path class: manipulating a path
  • Files class: file modification, attr related
  • FileSystem: info about file system

 

转载于:https://www.cnblogs.com/sansna/p/5390227.html

你可能感兴趣的文章
开发进度——4
查看>>
JS里验证信息
查看>>
Akka actor tell, ask 函数的实现
查看>>
windows10 chrome 调试 ios safari 方法
查看>>
Netty 4.1.35.Final 发布,经典开源 Java 网络服务框架
查看>>
详解Microsoft.AspNetCore.CookiePolicy
查看>>
SCDPM2012 R2实战一:基于SQL 2008 R2集群的SCDPM2012 R2的安装
查看>>
SQL SERVER中字段类型与C#数据类型的对应关系
查看>>
Linux lsof命令详解
查看>>
SVG path
查看>>
js判断checkbox是否选中
查看>>
多系统盘挂载
查看>>
MySQL函数怎么加锁_MYSQL 函数调用导致自动生成共享锁问题
查看>>
MR1和MR2的工作原理
查看>>
Eclipse中修改代码格式
查看>>
GRUB Legacy
查看>>
关于 error: LINK1123: failure during conversion to COFF: file invalid or corrupt 错误的解决方案...
查看>>
python实现链表
查看>>
java查找string1和string2是不是含有相同的字母种类和数量(string1是否是string2的重新组合)...
查看>>
Android TabActivity使用方法
查看>>