java7的新特性

来源:互联网 发布:海文网络班 编辑:程序博客网 时间:2024/05/22 18:22

具体参见原文 http://radar.oreilly.com/2011/09/java7-features.html


1:switch中可以使用字符串
2:泛型实例化类型自动推断 List<String> tempList = new ArrayList<>(); 
3:异常catch可以一次处理完而不像以前一层层的surround
try{
}catch(ExceptionOne| ExceptionTwo| ExceptionThree e){
//....
}
4:文件读写 会自动关闭流而不像以前那样需要在finally中显式close
public void newTry{
try(FileOutputStream  fos = new FileOutputStream("movies.txt");
DataOutputStream dos = new DataOutputStream(fos)){
dos.writeUTF("Java 7 Block Buster");  
}catch(IOException e){
//...
}

}
5:数值可以使用下划线分隔
int million = 1_000_000
6:文件读写功能增强,有更简单的api调用
public void pathInfo() {
            Path path = Paths.get("c:\\Temp\\temp");
System.out.println("Number of Nodes:" + path.getNameCount());
            System.out.println("File Name:" + path.getFileName());
            System.out.println("File Root:" + path.getRoot());
            System.out.println("File Parent:" + path.getParent()); 
            //这样写不会抛异常
            Files.deleteIfExists(path);
  }
7:文件改变的事件通知功能
private void init() {
      path = Paths.get("C:\\Temp\\temp\\");
      try {
            watchService = FileSystems.getDefault().newWatchService();
            path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      } catch (IOException e) {
            System.out.println("IOException"+ e.getMessage());
      }
}
private void doRounds() {
      WatchKey key = null;
      while(true) {
            try {
                  key = watchService.take();
                  for (WatchEvent<?> event : key.pollEvents()) {
                        Kind<?> kind = event.kind();
System.out.println("Event on " + event.context().toString() + " is " + kind);
                  }
            } catch (InterruptedException e) {
System.out.println("InterruptedException: "+e.getMessage());
            }
            boolean reset = key.reset();
            if(!reset)
                  break;
      }


}
8:多核,并行计算的支持加强fork join框架
ForkJoinPool pool = new ForkJoinPool(numberOfProcessors);
public class MyBigProblemTask extends RecursiveAction {
@Override
    protected void compute() {
        . . . // your problem invocation goes here
    }
}
pool.invoke(task);
9:还有一些动态特性的加入
java.lang.invoke包的引入。MethodHandle,CallSite还有一些其他类供使用