Java7新特性(二)IO
2013-11-21 15:27
253 查看
本文主要根据《Java程序员修炼之道》整理的代码笔记片段
回调式
其他:MulticastChannel Files.setPosixFilePermissions Files.readSymbolicLink Files.readAttributes(file, BasicFileAttributes.class);
1.Path
//查找目录下 文件 Path dir = Paths.get("E:\\Learn\\Java7\\trunk"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.properties")) { for (Path entry : stream) { System.out.println(entry.getFileName()); } } catch (IOException e) { System.out.println(e.getMessage()); }
Path listing = Paths.get("/usr/bin/zip"); System.out.println("File Name [" + listing.getFileName() + "]"); System.out.println("Number of Name Elements in the Path [" + listing.getNameCount() + "]"); System.out.println("Parent Path [" + listing.getParent() + "]"); System.out.println("Root of Path [" + listing.getRoot() + "]"); System.out.println("Subpath from Root, 2 elements deep [" + listing.subpath(0, 2) + "]");
2.Files.walkFileTree 遍历目录
public static void main(String[] args) throws IOException { Path startingDir = Paths.get("E:\\Learn\\Java7\\trunk"); //遍历目录 Files.walkFileTree(startingDir, new FindJavaVisitor()); } private static class FindJavaVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.toString().endsWith(".java")) { System.out.println(file.getFileName()); } return FileVisitResult.CONTINUE; } }
3.Files
try { Path zip = Paths.get("E:\\java\\test"); //Path zip = Paths.get("E:\\java\\测试.rar"); System.out.println(zip.toAbsolutePath().toString()); System.out.println(Files.getLastModifiedTime(zip)); System.out.println(Files.size(zip)); System.out.println(Files.isSymbolicLink(zip)); System.out.println(Files.isDirectory(zip)); System.out.println(Files.readAttributes(zip, "*")); } catch (IOException ex) { System.out.println("Exception" + ex.getMessage()); }
try { if(Files.exists(old)){ Files.copy(old, target, StandardCopyOption.REPLACE_EXISTING); Files.move(old, target2,StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
Path target = Paths.get("E:\\java\\test1.txt"); // try { // Files.delete(target); // } catch (IOException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-rw-rw-"); //FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); try { if(Files.notExists(target)){ Files.createFile(target); } } catch (IOException e) { e.printStackTrace(); }
4.读文件
Path old = Paths.get("E:\\java\\test.txt"); Path target = Paths.get("E:\\java\\test\\test1.txt"); try (BufferedReader reader = Files.newBufferedReader(old, StandardCharsets.UTF_8)){ String line ; while((line = reader.readLine())!=null){ System.out.println(line); } } catch (IOException e) { } try(BufferedWriter writer = Files.newBufferedWriter(target, StandardCharsets.UTF_8, StandardOpenOption.WRITE)){ writer.write("hello"); } catch (IOException e) { e.printStackTrace(); } try { @SuppressWarnings("unused") List<String> lines = Files.readAllLines(old, StandardCharsets.UTF_8); @SuppressWarnings("unused") byte[] bytes = Files.readAllBytes(old); } catch (IOException e) { e.printStackTrace(); } }
5.监听目录变化
//监听目录变化 try { WatchService watcher = FileSystems.getDefault().newWatchService(); Path dir = FileSystems.getDefault().getPath("E:\\java"); WatchKey key = dir.register(watcher, ENTRY_MODIFY); while (!shutdown) { key = watcher.take(); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == ENTRY_MODIFY) { System.out.println("Home dir changed!"); } } key.reset(); } } catch (IOException | InterruptedException e) { System.out.println(e.getMessage()); }
6.FileChannel通道截取
try { Path file = Paths.get("E:\\java\\test.txt"); FileChannel channel = FileChannel.open(file); ByteBuffer buffer = ByteBuffer.allocate(1024); channel.read(buffer, channel.size() -13); System.out.println((char)buffer.array()[0]); } catch (IOException e) { System.out.println(e.getMessage()); }
7.AsynchronousFileChannel 异步通道读取
将来式public class Listing_2_8 { //将来式 public static void main(String[] args) { try { Path file = Paths.get("E:\\java\\test.txt"); AsynchronousFileChannel channel = AsynchronousFileChannel.open(file); ByteBuffer buffer = ByteBuffer.allocate(100_000); Future<Integer> result = channel.read(buffer, 0); while (!result.isDone()) { ProfitCalculator.calculateTax(); } Integer bytesRead = result.get(); System.out.println("Bytes read [" + bytesRead + "]"); } catch (IOException | ExecutionException | InterruptedException e) { System.out.println(e.getMessage()); } } private static class ProfitCalculator { @SuppressWarnings("unused") public ProfitCalculator() { } public static void calculateTax() { System.out.println("test"); } } }
回调式
public class Listing_2_9 { //回调式 public static void main(String[] args) { try { Path file = Paths.get("E:\\java\\test.txt"); AsynchronousFileChannel channel = AsynchronousFileChannel.open(file); ByteBuffer buffer = ByteBuffer.allocate(100_000); channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() { public void completed(Integer result, ByteBuffer attachment) { //System.out.println("read"); System.out.println("Bytes read [" + result + "]"); } public void failed(Throwable exception, ByteBuffer attachment) { System.out.println(exception.getMessage()); } }); // System.out.println("test"); Thread.sleep(1000); } catch (IOException | InterruptedException e) { System.out.println(e.getMessage()); } } }
8.NetworkChannel 非阻塞网络套接字
SelectorProvider provider = SelectorProvider.provider(); try { NetworkChannel socketChannel = provider.openSocketChannel(); SocketAddress address = new InetSocketAddress(3080); socketChannel = socketChannel.bind(address); Set<SocketOption<?>> socketOptions = socketChannel.supportedOptions(); System.out.println(socketOptions.toString()); socketChannel.setOption(StandardSocketOptions.IP_TOS, 3); //System.out.println(socketChannel.getOption(StandardSocketOptions.IP_TOS)); Boolean keepAlive = socketChannel .getOption(StandardSocketOptions.SO_KEEPALIVE); // System.out.println(keepAlive); } catch (IOException e) { System.out.println(e.getMessage()); }
其他:MulticastChannel Files.setPosixFilePermissions Files.readSymbolicLink Files.readAttributes(file, BasicFileAttributes.class);
相关文章推荐
- Java7新特性(二)IO
- java7新特性IO操作Path
- java7新特性IO操作Files
- 11g新特性之IO校准(IO Calibration)
- 转贴:Mark Russinovich的Inside Vista Kernel系列文章,讲到了Vista内核的调度,IO,内存管理,缓存,事务处理,安全等众多新特性
- java7 新特性 总结版
- java7-java8新特性
- 谈谈我的微软特约稿:《SQL Server 2014 新特性:IO资源调控》
- java7的新特性
- Java7新特性--try-with-resources,自动关闭资源
- Hadoop IO 特性详解(1)
- Java7语法新特性:
- 学java7中的IO新类Path
- 转贴:Mark Russinovich的Inside Vista Kernel系列文章,讲到了Vista内核的调度,IO,内存管理,缓存,事务处理,安全等众多新特性
- 11g新特性之IO校准(IO Calibration)
- java7特性之 try-with-resources
- java7新特性:Try - with - Resources语句
- java7 新特性 总结版
- 转贴:Mark Russinovich的Inside Vista Kernel系列文章,讲到了Vista内核的调度,IO,内存管理,缓存,事务处理,安全等众多新特性
- JAVA7新特性