Java7新特性(二)IO

来源:互联网 发布:c语言!= 编辑:程序博客网 时间:2024/06/10 08:45

附上:java  7 TWR

5.try-with-resources(TWR) AutoCloseable


package com.java7developer.chapter1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class Java7ResourcesExample {
private void run() throws IOException {
File file = new File("foo");
URL url = null;
try {
url = new URL("http://www.google.com/");
} catch (MalformedURLException e) {
}
try (OutputStream out = new FileOutputStream(file);
InputStream is = url.openStream()) {
byte[] buf = new byte[4096];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
public static void main(String[] args) throws IOException {
Java7ResourcesExample instance = new Java7ResourcesExample();
instance.run();
}
}



本文主要根据《Java程序员修炼之道》整理的代码笔记片段

1.Path

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //查找目录下  文件  
  2. Path dir = Paths.get("E:\\Learn\\Java7\\trunk");  
  3. try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir,  
  4.     "*.properties")) {  
  5.   for (Path entry : stream) {  
  6.     System.out.println(entry.getFileName());  
  7.   }  
  8. catch (IOException e) {  
  9.   System.out.println(e.getMessage());  
  10. }  
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Path listing = Paths.get("/usr/bin/zip");  
  2.   
  3. System.out.println("File Name [" + listing.getFileName() + "]");  
  4. System.out.println("Number of Name Elements in the Path ["  
  5.     + listing.getNameCount() + "]");  
  6. System.out.println("Parent Path [" + listing.getParent() + "]");  
  7. System.out.println("Root of Path [" + listing.getRoot() + "]");  
  8. System.out.println("Subpath from Root, 2 elements deep ["  
  9.     + listing.subpath(02) + "]");  

2.Files.walkFileTree 遍历目录

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void main(String[] args) throws IOException {  
  2. ath startingDir = Paths.get("E:\\Learn\\Java7\\trunk");  
  3.   //遍历目录  
  4.   Files.walkFileTree(startingDir, new FindJavaVisitor());  
  5. }  
  6.   
  7. private static class FindJavaVisitor extends SimpleFileVisitor<Path> {  
  8.   
  9.   @Override  
  10.   public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {  
  11.   
  12.     if (file.toString().endsWith(".java")) {  
  13.       System.out.println(file.getFileName());  
  14.     }  
  15.     return FileVisitResult.CONTINUE;  
  16.   }  
  17. }  

3.Files

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. try {  
  2.   Path zip = Paths.get("E:\\java\\test");  
  3.   //Path zip = Paths.get("E:\\java\\测试.rar");  
  4.   System.out.println(zip.toAbsolutePath().toString());  
  5.   System.out.println(Files.getLastModifiedTime(zip));  
  6.   System.out.println(Files.size(zip));  
  7.   System.out.println(Files.isSymbolicLink(zip));  
  8.   System.out.println(Files.isDirectory(zip));  
  9.   System.out.println(Files.readAttributes(zip, "*"));  
  10. catch (IOException ex) {  
  11.   System.out.println("Exception" + ex.getMessage());  
  12. }  
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1.    try {  
  2.     if(Files.exists(old)){  
  3.         Files.copy(old, target, StandardCopyOption.REPLACE_EXISTING);  
  4.         Files.move(old, target2,StandardCopyOption.REPLACE_EXISTING);  
  5.     }  
  6.   
  7.    } catch (IOException e) {  
  8.     // TODO Auto-generated catch block  
  9.     e.printStackTrace();  
  10. }  
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1.     Path target = Paths.get("E:\\java\\test1.txt");  
  2. //    try {  
  3. //      Files.delete(target);  
  4. //  } catch (IOException e1) {  
  5. //      // TODO Auto-generated catch block  
  6. //      e1.printStackTrace();  
  7. //  }  
  8.       
  9.     Set<PosixFilePermission> perms =   
  10.             PosixFilePermissions.fromString("rw-rw-rw-");  
  11.       
  12.     //FileAttribute<Set<PosixFilePermission>> attr =   
  13.             PosixFilePermissions.asFileAttribute(perms);  
  14.       
  15.     try {  
  16.         if(Files.notExists(target)){  
  17.             Files.createFile(target);  
  18.         }  
  19.           
  20.     } catch (IOException e) {  
  21.           
  22.         e.printStackTrace();  
  23.     }  

4.读文件

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1.    Path old = Paths.get("E:\\java\\test.txt");  
  2.   
  3.    Path target = Paths.get("E:\\java\\test\\test1.txt");  
  4.   
  5.      
  6.    try (BufferedReader reader = Files.newBufferedReader(old, StandardCharsets.UTF_8)){  
  7.     String line ;  
  8.     while((line = reader.readLine())!=null){  
  9.         System.out.println(line);  
  10.     }  
  11. catch (IOException e) {  
  12.       
  13. }  
  14.      
  15.    try(BufferedWriter writer =   
  16.         Files.newBufferedWriter(target, StandardCharsets.UTF_8, StandardOpenOption.WRITE)){  
  17.     writer.write("hello");  
  18.    } catch (IOException e) {  
  19.   
  20.     e.printStackTrace();  
  21. }  
  22.      
  23.      
  24.    try {  
  25.     @SuppressWarnings("unused")  
  26.     List<String> lines = Files.readAllLines(old, StandardCharsets.UTF_8);  
  27.     @SuppressWarnings("unused")  
  28.     byte[] bytes = Files.readAllBytes(old);  
  29. catch (IOException e) {  
  30.       
  31.     e.printStackTrace();  
  32. }  
  33.      
  34.  }  

5.监听目录变化

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. //监听目录变化  
  2.    try {  
  3.      WatchService watcher = FileSystems.getDefault().newWatchService();  
  4.   
  5.      Path dir = FileSystems.getDefault().getPath("E:\\java");  
  6.   
  7.      WatchKey key = dir.register(watcher, ENTRY_MODIFY);  
  8.   
  9.      while (!shutdown) {  
  10.        key = watcher.take();  
  11.        for (WatchEvent<?> event : key.pollEvents()) {  
  12.          if (event.kind() == ENTRY_MODIFY) {  
  13.            System.out.println("Home dir changed!");  
  14.          }  
  15.        }  
  16.        key.reset();  
  17.      }  
  18.    } catch (IOException | InterruptedException e) {  
  19.      System.out.println(e.getMessage());  
  20.    }  

6.FileChannel通道截取

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. try {  
  2.   Path file = Paths.get("E:\\java\\test.txt");  
  3.   
  4.   FileChannel channel = FileChannel.open(file);  
  5.   
  6.   ByteBuffer buffer = ByteBuffer.allocate(1024);  
  7.   channel.read(buffer, channel.size() -13);  
  8.    
  9. tem.out.println((char)buffer.array()[0]);  
  10.   
  11.    
  12. catch (IOException e) {  
  13.   System.out.println(e.getMessage());  
  14. }  

7.AsynchronousFileChannel 异步通道读取

将来式
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class Listing_2_8 {  
  2.   
  3.   //将来式  
  4.   public static void main(String[] args) {  
  5.     try {  
  6.       Path file = Paths.get("E:\\java\\test.txt");  
  7.   
  8.       AsynchronousFileChannel channel = AsynchronousFileChannel.open(file);  
  9.   
  10.       ByteBuffer buffer = ByteBuffer.allocate(100_000);  
  11.       Future<Integer> result = channel.read(buffer, 0);  
  12.   
  13.       while (!result.isDone()) {  
  14.         ProfitCalculator.calculateTax();  
  15.       }  
  16.   
  17.       Integer bytesRead = result.get();  
  18.       System.out.println("Bytes read [" + bytesRead + "]");  
  19.     } catch (IOException | ExecutionException | InterruptedException e) {  
  20.       System.out.println(e.getMessage());  
  21.     }  
  22.   }  
  23.   
  24.   private static class ProfitCalculator {  
  25.   
  26.     @SuppressWarnings("unused")  
  27.     public ProfitCalculator() {  
  28.     }  
  29.   
  30.     public static void calculateTax() {  
  31.         System.out.println("test");  
  32.     }  
  33.   }  
  34. }  
回调式
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class Listing_2_9 {  
  2.   //回调式  
  3.   public static void main(String[] args) {  
  4.     try {  
  5.       Path file = Paths.get("E:\\java\\test.txt");  
  6.       AsynchronousFileChannel channel = AsynchronousFileChannel.open(file);  
  7.   
  8.       ByteBuffer buffer = ByteBuffer.allocate(100_000);  
  9.   
  10.       channel.read(buffer, 0, buffer,  
  11.           new CompletionHandler<Integer, ByteBuffer>() {  
  12.   
  13.             public void completed(Integer result, ByteBuffer attachment) {  
  14.                 //System.out.println("read");  
  15.                 System.out.println("Bytes read [" + result + "]");  
  16.                   
  17.             }  
  18.   
  19.             public void failed(Throwable exception, ByteBuffer attachment) {  
  20.               System.out.println(exception.getMessage());  
  21.             }  
  22.           });  
  23.      // System.out.println("test");  
  24.       Thread.sleep(1000);  
  25.         
  26.     } catch (IOException | InterruptedException e) {  
  27.       System.out.println(e.getMessage());  
  28.     }  
  29.   }  
  30. }  

8.NetworkChannel 非阻塞网络套接字

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. SelectorProvider provider = SelectorProvider.provider();  
  2. try {  
  3.   NetworkChannel socketChannel = provider.openSocketChannel();  
  4.   SocketAddress address = new InetSocketAddress(3080);  
  5.   socketChannel = socketChannel.bind(address);  
  6.   
  7.   Set<SocketOption<?>> socketOptions = socketChannel.supportedOptions();  
  8.   
  9.   System.out.println(socketOptions.toString());  
  10.     
  11.   socketChannel.setOption(StandardSocketOptions.IP_TOS, 3);  
  12.   //System.out.println(socketChannel.getOption(StandardSocketOptions.IP_TOS));  
  13.   Boolean keepAlive = socketChannel  
  14.       .getOption(StandardSocketOptions.SO_KEEPALIVE);  
  15.  // System.out.println(keepAlive);  
  16.    
  17. } catch (IOException e) {  
  18.   System.out.println(e.getMessage());  
  19. }  

其他:MulticastChannel  Files.setPosixFilePermissions  Files.readSymbolicLink Files.readAttributes(file, BasicFileAttributes.class);
0 0
原创粉丝点击