您的位置:首页 > 编程语言 > Java开发

Java7新特性(二)IO

2013-11-21 15:27 253 查看
本文主要根据《Java程序员修炼之道》整理的代码笔记片段

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: