大家好,欢迎来到IT知识分享网。
jdk7&8 的架构图
1、Java 编程语言特性
- 1.1二进制数字表达方式
the integral types (byte, short, int, and long) can also be expressed using the binary number system。例如:
byte aByte = (byte)0b00; // An 8-bit 'byte' value short aShort = (short)0b00101; // A 16-bit 'short' value: int anInt1 = 0b000; // Some 32-bit 'int' values int anInt2 = 0b101; int anInt3 = 0B101; // The B can be upper or lower case.1.2 使用下划线对数字进行分隔表达,例如可表示: 1_322_222
- 1.3 switch 语句支持字符串变量,例如:switch (String str) {…}
- 1.4 泛型实例创建的类型推断,例如: 使用可变参数时,提升编译器的警告和错误信息
Map<String, List<String>> myMap = new HashMap<>();// an empty set of type parameters (<>) to init constructor. List<? extends String> list2 = new ArrayList<>(); list.addAll(list2); - 1.5 try-with-resources 语句
说明:The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource
格式:
try(// open resources here){ // use resources } catch (FileNotFoundException e) { // exception handling } // resources are closed as soon as try-catch block is executed.优点:
- 代码的可读性更好,更易于编写代码
- 自动化的资源管理
- 代码的行数被减少
- 不需要使用finally块来关闭资源
我们可以通过在try-with-resources中使用分号来间隔多个资源,例子:
try ( BufferedReader br = new BufferedReader(new FileReader("C:\\python.txt")); java.io.BufferedWriter writer=java.nio.file.Files. newBufferedWriter(FileSystems.getDefault().getPath("C:\\journaldev.txt"), Charset.defaultCharset())) { System.out.println(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
1.6 同时捕获多个异常处理 1)Handling More Than One Type of Exception:a single catch block can handle more than one type of exception,例如:catch (IOException|SQLException ex) {} 2)Rethrowing Exceptions with More Inclusive Type Checking:rethrow exception allows you to specify more specific exception types in the throws clause of a method declaration。例如:
package com.journaldev.util; public class Java7MultipleExceptions { public static void main(String[] args) { try{ rethrow("abc"); }catch(FirstException | SecondException | ThirdException e){ //below assignment will throw compile time exception since e is final //e = new Exception(); System.out.println(e.getMessage()); } } static void rethrow(String s) throws FirstException, SecondException,ThirdException { try { if (s.equals("First")) throw new FirstException("First"); else if (s.equals("Second")) throw new SecondException("Second"); else throw new ThirdException("Third"); } catch (Exception e) { //below assignment disables the improved rethrow exception type checking feature of Java 7 // e=new ThirdException(); throw e; } } static class FirstException extends Exception { public FirstException(String msg) { super(msg); } } ....... static class ThirdException extends Exception { public ThirdException(String msg) { super(msg); } } }
2.1 fork/join 框架(分而治之框架)
Fork 原始含义叉子、分叉的意思。在Linux 平台中,函数 fork()用来创建子进程,使得系统进程可以多一个执行分支; Join表示等待。fork()后系统多一个执行分支-线程,需要等待此执行分支执行完毕,才有可能得到结果,因此 join 就是表示等待。
实际使用中,如果大量使用 fork 开启线程进行处理,那么可能导致系统由过多线程而严重影响性能。故JDK给出ForkJoinPool 线程池,将fork开启线程交给ForkJoiinPool 线程池进行处理,节省系统资源。ForkJoinPool来支持将一个任务拆分成多个“小任务”并行计算,再把多个“小任务”的结果合并成总的计算结果。
ForkJoinPool是ExecutorService的实现类,因此是一种特殊的线程池。
使用方法:1)初始化 ForkJoinPool commonPool = ForkJoinPool.commonPool(); 2)执行指定任务commonPool.submit(ForkJoinTask<T> task) 或invoke(ForkJoinTask<T> task)。ForkJoinTask代表并行、合并的任务;ForkJoinTask是一个抽象类,它还有两个抽象子类:RecusiveAction(返回值任务)和RecusiveTask(无返回值任务)
RecusiveAction(返回值任务)和RecusiveTask(无返回值任务) Demo见:https://www.cnblogs.com/lixuwu/p/7979480.html
2.4 IO
2.4.1 递归查找文件树
Files.walkFileTree(Path filepath,class T extends SimpleFileVisitor<Path>)
DEMO:
import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.regex.Matcher; import java.util.regex.Pattern; / * @Description : 遍历目录树中的.java .class程序文件 */ public class Test { public static void main(String[] args) throws IOException { Path path = Paths.get(""); System.out.println(path.toAbsolutePath()); String regex = "^.+?\\.(?:(?:java)||(?:class))$"; final Pattern pattern = Pattern.compile(regex); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String f = file.toString(); Matcher m = pattern.matcher(f); if (m.matches()) { System.out.println(f); } return FileVisitResult.CONTINUE; } }); } }
2.4.2 文件系统修改通知
import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import static java.nio.file.StandardWatchEventKind.*; / *JDK7 文件系统修改通知机制 */ public class TestWatcherService { private WatchService watcher; public TestWatcherService(Path path)throws IOException{ watcher = FileSystems.getDefault().newWatchService(); //1 newWatchService方法实例化WatchService监听服务 path.register(watcher, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY); //2 目录注册,watcher监听目录操作事件创建、删除、修改 } public void handleEvents() throws InterruptedException{ while(true){ WatchKey key = watcher.take(); for(WatchEvent<?> event : key.pollEvents()){ WatchEvent.Kind kind = event.kind(); //3 获取事件Event,Event :ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY if(kind == OVERFLOW){//事件可能lost or discarded continue; } WatchEvent<Path> e = (WatchEvent<Path>)event; Path fileName = e.context(); System.out.printf("Event %s has happened, which fileName is %s%n" ,kind.name(),fileName); } if(!key.reset()){ break; } } } }
PS:https://www.journaldev.com/588/java-switch-case-string
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/111060.html

