Pro Java 7 NIO 2 读书笔记
Pro Java 7 NIO 2 读书笔记
花了几天把这本书初略的看了一下, 之所以初略的看了一下,是因为这书里确实没啥内容。如果去了NIO 1的内容和大段大段的代码, 基本上压缩到50页应该没问题。
下面简单的罗列一下看到的内容:
Path
这个类在java.nio.file,在NIO里对文件系统进行了进一步的抽象。 是用来替换原来的java.io.File。其中 FileSystems, Files, Path, PathMatcher 成为一个体系。
在java7里File和Path可以相互转换: File.toPath(), Path.toFile()
原来的File里包含了文件引用和文件,在Path系统里, Path里是文件的引用,而文件操作都放到了Files的静态方法里。这种方式究竟好不好用,我没啥感觉。不过我跟人偏向于把操作放到另外一个类里面。
获得Path实例的方式:
File.toPath(), Paths.get(), FileSystem.getPath()
Paths.get("C:","folder1","subfolder","aa.txt")//define the fixed pathPath base = Paths.get("C:/rafaelnadal/tournaments/2009");//resolve BNP.txt filePath path_1 = base.resolve("BNP.txt");//output: C:\rafaelnadal\tournaments\2009\BNP.txtSystem.out.println(path_1.toString());//resolve AEGON.txt filePath path_2 = base.resolve("AEGON.txt");//output: C:\rafaelnadal\tournaments\2009\AEGON.txtSystem.out.println(path_2.toString());//define the fixed pathPath base = Paths.get("C:/rafaelnadal/tournaments/2009/BNP.txt");//resolve sibling AEGON.txt filePath path = base.resolveSibling("AEGON.txt");//output: C:\rafaelnadal\tournaments\2009\AEGON.txtSystem.out.println(path.toString());Path path01 = Paths.get("BNP.txt");Path path02 = Paths.get("AEGON.txt");//output: ..\AEGON.txtPath path01_to_path02 = path01.relativize(path02);System.out.println(path01_to_path02);//output: ..\BNP.txtPath path02_to_path01 = path02.relativize(path01);System.out.println(path02_to_path01);Path path01 = Paths.get("/tournaments/2009/BNP.txt");Path path02 = Paths.get("/tournaments/2011");//output: ..\..\2011Path path01_to_path02 = path01.relativize(path02);System.out.println(path01_to_path02);//output: ..\2009\BNP.txtPath path02_to_path01 = path02.relativize(path01);System.out.println(path02_to_path01);
Path path = Paths.get("C:", "rafaelnadal/tournaments/2009", "BNP.txt");for (Path name : path) { System.out.println(name);}BasicFileAttributes attr = null;Path path = Paths.get("C:/rafaelnadal/tournaments/2009", "BNP.txt");try { attr = Files.readAttributes(path, BasicFileAttributes.class);} catch (IOException e) { System.err.println(e);}System.out.println("File size: " + attr.size());System.out.println("File creation time: " + attr.creationTime());System.out.println("File was last accessed at: " + attr.lastAccessTime());System.out.println("File was last modified at: " + attr.lastModifiedTime());System.out.println("Is directory? " + attr.isDirectory());System.out.println("Is regular file? " + attr.isRegularFile());System.out.println("Is symbolic link? " + attr.isSymbolicLink());System.out.println("Is other? " + attr.isOther());long size = (Long)Files.getAttribute(path, "basic:size", NOFOLLOW_LINKS);
Path path = Paths.get("C:/rafaelnadal/tournaments/2009", "BNP.txt");long time = System.currentTimeMillis();FileTime fileTime = FileTime.fromMillis(time);try { Files.getFileAttributeView(path, BasicFileAttributeView.class).setTimes(fileTime, fileTime, fileTime);} catch (IOException e) { System.err.println(e);}long time = System.currentTimeMillis();FileTime fileTime = FileTime.fromMillis(time);try { Files.setLastModifiedTime(path, fileTime);} catch (IOException e) { System.err.println(e);}Path link = FileSystems.getDefault().getPath("rafael.nadal.1");Path target= FileSystems.getDefault().getPath("C:/rafaelnadal/photos", "rafa_winner.jpg");Files.createSymbolicLink(link, target);Path path = Paths.get("C:/rafaelnadal/tournaments/2009");…//glob pattern appliedSystem.out.println("\nGlob pattern applied:");try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, "*.{png,jpg,bmp}")) { for (Path file : ds) { System.out.println(file.getFileName()); }} catch (IOException e) { System.err.println(e);}FileVisitResult postVisitDirectory(T dir, IOException exc) Invoked for a directory after entries in the directory, and all of their descendants, have been visited.FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) Invoked for a directory before entries in the directory are visited.FileVisitResult visitFile(T file, BasicFileAttributes attrs) Invoked for a file in a directory.FileVisitResult visitFileFailed(T file, IOException exc) Invoked for a file that could not be visited.
CONTINUE,SKIP_SIBLINGS,SKIP_SUBTREE,TERMINATE
public void watchRNDir(Path path) throws IOException, InterruptedException { try (WatchService watchService = FileSystems.getDefault().newWatchService()) { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); //start an infinite loop while (true) { //retrieve and remove the next watch key final WatchKey key = watchService.take(); //get list of pending events for the watch key for (WatchEvent<?> watchEvent : key.pollEvents()) { //get the kind of event (create, modify, delete) final Kind<?> kind = watchEvent.kind(); //handle OVERFLOW event if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); //print it out System.out.println(kind + " -> " + filename); } //reset the key boolean valid = key.reset(); //exit loop if the key is not valid (if the directory was deleted, for example) if (!valid) { break; } } }} Path path = Paths.get("C:/rafaelnadal/tournaments/2009", "MovistarOpen.txt");ByteBuffer buffer = ByteBuffer.allocate(1);String encoding = System.getProperty("file.encoding");try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path, EnumSet.of(StandardOpenOption.READ)))) { //the initial position should be 0 anyway seekableByteChannel.position(0); System.out.println("Reading one character from position: " + seekableByteChannel.position()); seekableByteChannel.read(buffer); buffer.flip(); System.out.print(Charset.forName(encoding).decode(buffer)); buffer.rewind(); //get into the middle seekableByteChannel.position(seekableByteChannel.size()/2); System.out.println("\nReading one character from position: " + seekableByteChannel.position()); seekableByteChannel.read(buffer); buffer.flip(); System.out.print(Charset.forName(encoding).decode(buffer)); buffer.rewind(); //get to the end seekableByteChannel.position(seekableByteChannel.size()-1); System.out.println("\nReading one character from position: " + seekableByteChannel.position()); seekableByteChannel.read(buffer); buffer.flip(); System.out.print(Charset.forName(encoding).decode(buffer)); buffer.clear();} catch (IOException ex) { System.err.println(ex);}ByteBuffer buffer = ByteBuffer.allocate(100);Path path = Paths.get("C:/rafaelnadal/grandslam/RolandGarros", "story.txt");try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) { current = Thread.currentThread(); asynchronousFileChannel.read(buffer, 0, "Read operation status ...", new CompletionHandler<Integer, Object>() { @Override public void completed(Integer result, Object attachment) { System.out.println(attachment); System.out.print("Read bytes: " + result); current.interrupt(); } @Override public void failed(Throwable exc, Object attachment) { System.out.println(attachment); System.out.println("Error:" + exc); current.interrupt(); } }); System.out.println("\nWaiting for reading operation to end ...\n"); try { current.join(); } catch (InterruptedException e) { } //now the buffer contains the read bytes System.out.println("\n\nClose everything and leave! Bye, bye ...");} catch (Exception ex) { System.err.println(ex);}public class AsyncEchoServer { private AsynchronousServerSocketChannel serverChannel; public void start() throws IOException { System.out.println(String.format("start: name: %s", Thread.currentThread().getName())); serverChannel = AsynchronousServerSocketChannel.open(); serverChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); serverChannel.bind(new InetSocketAddress(8000)); serverChannel.accept(serverChannel, new Acceptor()); } class Acceptor implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> { private final ByteBuffer buffer = ByteBuffer.allocate(1024); public Acceptor(){ System.out.println("an acceptor has created."); } public void completed(final AsynchronousSocketChannel channel, AsynchronousServerSocketChannel serverChannel) { System.out.println(String.format("write: name: %s", Thread.currentThread().getName())); channel.read(buffer, channel, new Reader(buffer)); serverChannel.accept(serverChannel, new Acceptor()); } public void failed(Throwable exception, AsynchronousServerSocketChannel serverChannel) { throw new RuntimeException(exception); } } class Reader implements CompletionHandler<Integer, AsynchronousSocketChannel> { private ByteBuffer buffer; public Reader(ByteBuffer buffer){ this.buffer = buffer; } public void completed(Integer result, AsynchronousSocketChannel channel){ System.out.println(String.format("read: name: %s", Thread.currentThread().getName())); if(result != null && result < 0){ try{ channel.close(); return; }catch(IOException ignore){} } buffer.flip(); channel.write(buffer, channel, new Writer(buffer)); } public void failed(Throwable exception, AsynchronousSocketChannel channel){ throw new RuntimeException(exception); } } class Writer implements CompletionHandler<Integer, AsynchronousSocketChannel> { private ByteBuffer buffer; public Writer(ByteBuffer buffer){ this.buffer = buffer; } public void completed(Integer result, AsynchronousSocketChannel channel) { System.out.println(String.format("write: name: %s", Thread.currentThread().getName())); buffer.clear(); channel.read(buffer, channel, new Reader(buffer)); } public void failed(Throwable exception, AsynchronousSocketChannel channel) { throw new RuntimeException(exception); } } public static void main(String[] args) throws IOException, InterruptedException{ new AsyncEchoServer().start(); while(true){ Thread.sleep(1000L); } }}