java7 nio2 新特性_JDK7新特性,你知道几个?

前言

之前学习的过程中,每天都是老师说这个是JDK7以后可以使用,那个是JDK8以后可以使用,每天都记的很混乱,今天专门忙里偷闲,归拢整理下JDK7的新特性,对于JDK的新特性,后期会进行整理更新,希望可以帮助到有需要的朋友。

一,语法上

1.1switch中可以使用字串了

String s = "test";

switch (s) {

case "test" :

System.out.println("test");

case "test1" :

System.out.println("test1");

break ;

default :

System.out.println("break");

break ;

}

1.2二进制变量的表示,支持将整数类型用二进制来表示,用0b开头。

// 所有整数 int, short,long,byte都可以用二进制表示

// An 8-bit 'byte' value:

byte aByte = (byte) 0b00100001;

// A 16-bit 'short' value:

short aShort = (short) 0b1010000101000101;

// Some 32-bit 'int' values:

intanInt1 = 0b10100001010001011010000101000101;

intanInt2 = 0b101;

intanInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' value. Note the "L" suffix:

long aLong =

0b1010000101000101101000010100010110100001010001011010000101000101L;

// 二进制在数组等的使用

final int[] phases = { 0b00110001, 0b01100010, 0b11000100, 0b10001001,0b00010011, 0b00100110, 0b01001100, 0b10011000 };

1.3 Try-with-resource语句

注意:实现java.lang.AutoCloseable接口的资源都可以放到try中,跟final里面的关闭资源类似; 按照声明逆序关闭资源 ;Try块抛出的异常通过Throwable.getSuppressed获取

try (java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);

java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)) {

// Enumerate each entry

for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements()) {

// Get the entry name and write it to the output file

String newLine = System.getProperty("line.separator");

String zipEntryName = ((java.util.zip.ZipEntry) entries

.nextElement()).getName() + newLine;

writer.write(zipEntryName, 0, zipEntryName.length());

}

}

}

1.4 Catch多个异常 说明:Catch异常类型为final; 生成Bytecode 会比多个catch小; Rethrow时保持异常类型

public static void main(String[] args) throws Exception {

try {

testthrows();

} catch (IOException | SQLException ex) {

throw ex;

}

}

public static void testthrows() throws IOException, SQLException {}

1.5 数字类型的下划线表示 更友好的表示方式,不过要注意下划线添加的一些标准,可以参考下面的示例

long creditCardNumber = 1234_5678_9012_3456L;

long socialSecurityNumber = 999_99_9999L;

float pi = 3.14_15F;

long hexBytes = 0xFF_EC_DE_5E;

long hexWords = 0xCAFE_BABE;

long maxLong = 0x7fff_ffff_ffff_ffffL;

byte nybbles = 0b0010_0101;

long bytes = 0b11010010_01101001_10010100_10010010;

//float pi1 = 3_.1415F;// Invalid; cannot put underscores adjacent to a decimal point

//float pi2 = 3._1415F;// Invalid; cannot put underscores adjacent to a decimal point

//long socialSecurityNumber1= 999_99_9999_L;// Invalid; cannot put underscores prior to an L suffix

//int x1 = _52;// This is an identifier, not a numeric literal

int x2 = 5_2;// OK (decimal literal)

//int x3 = 52_;// Invalid; cannot put underscores at the end of a literal

int x4 = 52;// OK (decimal literal)

//int x5 = 0_x52;// Invalid; cannot put underscores in the 0x radix prefix

//int x6 = 0x_52;// Invalid; cannot put underscores at the beginning of a number

int x7 = 0x5_2;// OK (hexadecimal literal)

//int x8 = 0x52_;// Invalid; cannot put underscores at the end of a number

int x9 = 0_52; // OK (octal literal)

int x10 = 05_2;// OK (octal literal)

//int x11 = 052_;// Invalid; cannot put underscores at the end of a number

1.6 泛型实例的创建可以通过类型推断来简化 可以去掉后面new部分的泛型类型,只用<>就可以了。

//使用泛型前

List strList = new ArrayList();

List strList4 = new ArrayList();

List>> strList5 = new ArrayList>>();

//编译器使用尖括号 (<>) 推断类型

List strList0 = new ArrayList();

List>> strList1 = new ArrayList>>();

List strList2 = new ArrayList<>();

List>> strList3 = new ArrayList<>();

List list = new ArrayList<>();

list.add("A");

// The following statement should fail since addAll expects

// Collection extends String>

//list.addAll(new ArrayList<>());

1.7在可变参数方法中传递非具体化参数,改进编译警告和错误

Heap pollution 指一个变量被指向另外一个不是相同类型的变量。例如

List l = new ArrayList();

List ls = l; // unchecked warning

l.add(0, new Integer(42)); // another unchecked warning

String s = ls.get(0); // ClassCastException is thrown

Jdk7:

public static void addToList (List listArg, T... elements) {

for (T x : elements) {

listArg.add(x);

}

}

你会得到一个warning

warning: [varargs] Possible heap pollution from parameterized vararg type

要消除警告,可以有三种方式

1.加 annotation @SafeVarargs

2.加 annotation @SuppressWarnings({"unchecked", "varargs"})

3.使用编译器参数 –Xlint:varargs;

1.8 信息更丰富的回溯追踪 就是上面try中try语句和里面的语句同时抛出异常时,异常栈的信息

java.io.IOException at Suppress.write(Suppress.java:19)at Suppress.main(Suppress.java:8)

Suppressed: java.io.IOException at Suppress.close(Suppress.java:24)

at Suppress.main(Suppress.java:9)

Suppressed: java.io.IOException at Suppress.close(Suppress.java:24)

at Suppress.main(Suppress.java:9)

二、NIO2的一些新特性

java.nio.file 和java.nio.file.attribute包 支持更详细属性,比如权限,所有者

symbolic and hard links支持

Path访问文件系统,Files支持各种文件操作

高效的访问metadata信息

递归查找文件树,文件扩展搜索

文件系统修改通知机制

File类操作API兼容

文件随机访问增强 mapping a region,locl a region,绝对位置读取

AIO Reactor(基于事件)和Proactor

下面列一些示例:

2.1 IO and New IO 监听文件系统变化通知

通过FileSystems.getDefault().newWatchService()获取watchService,然后将需要监听的path目录注册到这个watchservice中,对于这个目录的文件修改,新增,删除等实践可以配置,然后就自动能监听到响应的事件。

private WatchService watcher;

public TestWatcherService(Path path) throws IOException {

watcher = FileSystems.getDefault().newWatchService();

path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

}

public void handleEvents() throws InterruptedException {

while (true) {

WatchKey key = watcher.take();

for (WatchEvent> event : key.pollEvents()) {

WatchEvent.Kind kind = event.kind();

if (kind == OVERFLOW) {// 事件可能lost or discarded

continue;

}

WatchEvent e = (WatchEvent) event;

Path fileName = e.context();

System.out.printf("Event %s has happened,which fileName is %s%n",kind.name(), fileName);

}

if (!key.reset()) {

break;

}

2.2 IO and New IO遍历文件树,通过继承SimpleFileVisitor类,实现事件遍历目录树操作,然后通过Files.walkFileTree(listDir, opts,Integer.MAX_VALUE, walk);这个API来遍历目录树

private void workFilePath() {

Path listDir = Paths.get("/tmp"); // define the starting file

ListTree walk = new ListTree();

Files.walkFileTree(listDir, walk);

// 遍历的时候跟踪链接

EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

try {

Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);

} catch (IOException e) {

System.err.println(e);

}

class ListTree extends SimpleFileVisitor {// NIO2 递归遍历文件目录的接口

@Override

public FileVisitResult postVisitDirectory(Path dir, IOException exc) {

System.out.println("Visited directory: " + dir.toString());

return FileVisitResult.CONTINUE;

}

@Override

public FileVisitResult visitFileFailed(Path file, IOException exc) {

System.out.println(exc);

return FileVisitResult.CONTINUE;

}

}

2.3 AIO异步IO 文件和网络 异步IO在java

NIO2实现了,都是用AsynchronousFileChannel,AsynchronousSocketChanne等实现,关于同步阻塞IO,同步非阻塞IO,异步阻塞IO和异步非阻塞IO在ppt的这页上下面备注有说明,有兴趣的可以深入了解下。Java NIO2中就实现了操作系统的异步非阻塞IO。

// 使用AsynchronousFileChannel.open(path, withOptions(),taskExecutor))这个API对异步文件IO的处理

public static void asyFileChannel2() {

final int THREADS = 5;

ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);

String encoding = System.getProperty("file.encoding");

List> list = new ArrayList<>();

int sheeps = 0;

Path path = Paths.get("/tmp","store.txt");

try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, withOptions(), taskExecutor)) {

for (int i = 0; i < 50; i++) {

Callable worker = new Callable(){

@Override

public ByteBuffer call() throws Exception {

ByteBuffer buffer = ByteBuffer.allocateDirect(ThreadLocalRandom.current().nextInt(100, 200));

asynchronousFileChannel.read(buffer, ThreadLocalRandom)

……

三. JDBC 4.1

3.1.可以使用try-with-resources自动关闭Connection, ResultSet, 和 Statement资源对象

3.2. RowSet 1.1:引入RowSetFactory接口和RowSetProvider类,可以创建JDBC driver支持的各种 row sets,这里的rowset实现其实就是将sql语句上的一些操作转为方法的操作,封装了一些功能。

3.3. JDBC-ODBC驱动会在jdk8中删除

try (Statement stmt = con.createStatement()) {

RowSetFactory aFactory = RowSetProvider.newFactory();

CachedRowSet crs = aFactory.createCachedRowSet();

RowSetFactory rsf = RowSetProvider.newFactory("com.sun.rowset.RowSetFactoryImpl", null);

WebRowSet wrs = rsf.createWebRowSet();

createCachedRowSet

createFilteredRowSet

createJdbcRowSet

createJoinRowSet

createWebRowSet

}

四、并发工具增强

4.1.fork-join

最大的增强,充分利用多核特性,将大问题分解成各个子问题,由多个cpu可以同时解决多个子问题,最后合并结果,继承RecursiveTask,实现compute方法,然后调用fork计算,最后用join合并结果。

class Fibonacci extends RecursiveTask {

final int n;

Fibonacci(int n) {

this.n = n;

}

private int compute(int small) {

final int[] results = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };

return results[small];

}

public Integer compute() {

if (n <= 10) {

return compute(n);

}

Fibonacci f1 = new Fibonacci(n - 1);

Fibonacci f2 = new Fibonacci(n - 2);

System.out.println("fork new thread for " + (n - 1));

f1.fork();

System.out.println("fork new thread for " + (n - 2));

f2.fork();

return f1.join() + f2.join();

}

}

4.2.ThreadLocalRandon 并发下随机数生成类,保证并发下的随机数生成的线程安全,实际上就是使用threadlocal

final int MAX = 100000;

ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();

long start = System.nanoTime();

for (int i = 0; i < MAX; i++) {

threadLocalRandom.nextDouble();

}

long end = System.nanoTime() - start;

System.out.println("use time1 : " + end);

long start2 = System.nanoTime();

for (int i = 0; i < MAX; i++) {

Math.random();

}

long end2 = System.nanoTime() - start2;

System.out.println("use time2 : " + end2);

4.3. phaser 类似cyclebarrier和countdownlatch,不过可以动态添加资源减少资源

void runTasks(List tasks) {

final Phaser phaser = new Phaser(1); // "1" to register self

// create and start threads

for (final Runnable task : tasks) {

phaser.register();

new Thread() {

public void run() {

phaser.arriveAndAwaitAdvance(); // await all creation

task.run();

}

}.start();

}

// allow threads to start and deregister self

phaser.arriveAndDeregister();

}

结尾

由于个人能力问题,还有很多需要改进的地方,如有错误,烦请各位大佬私信或留言进行批评指正,在下定当及时更正!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/566465.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java jsp校验提示信息_java Jquery表单校验代码jsp页面

jsp.file欢迎注册EasyMall/* 注册表单的js校验 */var formObj {/* 检查输入项是否为空 */"checkNull" : function(name, msg){var value $("input[name"name"]").val().trim();//清空之前的提示消息formObj.setMsg(name, "");if(val…

错误处理方法 java_JAVA常见错误处理方法 和 JVM内存结构

OutOfMemoryError在开发过程中是司空见惯的&#xff0c;遇到这个错误&#xff0c;新手程序员都知道从两个方面入手来解决&#xff1a;一是排查程序是否有BUG导致内存泄漏&#xff1b;二是调整JVM启动参数增大内存。OutOfMemoryError有好几种情况&#xff0c;每次遇到这个错误时…

java中如何分隔字符串_Java中分割字符串

java.lang.String的split()方法, JDK 1.4 or laterpublic String[] split(String regex,int limit)示例代码public classStringSplit {public static voidmain(String[] args) {String sourceStr "1,2,3,4,5";String[] sourceStrArray sourceStr.split(",&quo…

typescript 接口 java_Typescript基础(4)——接口

前言今天继续typescript的学习&#xff0c;开始ts接口部分的学习。接口接口的理解首先&#xff0c;我们谈论一下现实生活中的接口。比如生活中常用的插座接口&#xff0c;有些插头是三孔插座的&#xff0c;有些是两孔插座的。插座接口规定了插头的数目&#xff0c;那么我们的电…

php测试号推送消息失败,信息发送失败是什么原因

手机突然信息发送失败可能是以下原因&#xff1a;1.是因为我们的手机出现了欠费的情况,所以发不出短信,这种情况是最为普遍的,需要我们及时的进行缴费。2.手机的信息中心的号码设置有误,应该根据你所在省份的实际信息中心号码进行设置,这样一般就能解决这方面的问题。可能是你的…

php ajax 概率 转盘,php+jquery实现转盘抽奖 概率可任意调

phpjquery实现转盘抽奖 概率可任意调phpjquery实现转盘抽奖 概率可任意调Posted by: xiaomiao 2014/05/13in Code, PHP 3 Commentsphpjquery实现转盘抽奖查看DEMO演示转盘抽奖&#xff0c;炫丽的一般是flash做的。不懂flash而又不需要那么炫丽&#xff0c;可以简单的通过jquer…

组件php53 php55区别,分享下php5类中三种数据类型的区别

public: 公有类型    在子类中可以通过self::var 来调用 public类型的方法或属性 可以通过parent::method 来调用父类中的方法在实例中可以能过$obj->var 来调用 public类型的方法或属性protected: 受保护类型在子类中可以通过self::var 来调用 protected类型的方法…

wins宝塔安装提示已经有php,centOS安装宝塔提示报错

安装宝塔提示这个错误、一般是DNS问题、或者更换个安装节点P rootlocalhost:~root0104.223.166.114s password: ILast failed login: Tue Jul 17 02:32:19 EDT 2018 from 112.85.42.197 on. ssh :notty IThere were 780 failed login attempts since the last successful login…

php自动抓取文章图片,从文章中提取图片,把图片保存到本地,自动提取缩略图...

开发二代旅游网站程序和CMS的时候&#xff0c;有一个需求&#xff0c;就是从网上复制的内容&#xff0c;里面包含图片的&#xff0c;需要对把图片提取出来&#xff0c;并且保存到本地&#xff0c;并且把图片的URL地址本地化&#xff0c;以下是实现的代码。开发二代旅游网站程序…

url get参数 php,怎么取得Url中Get参数

这次给大家带来怎么取得Url中Get参数&#xff0c;取得Url中Get参数的注意事项有哪些&#xff0c;下面就是实战案例&#xff0c;一起来看一下。此时可以使用js的方式得到当前页面的url中的get参数. 核心语句是:window.location.href详细代码不解释了,有注释,你看了就懂.封装成jQ…

php tls,使用TLS在PHP中建立连接

我为特殊目的编写了一个小型SIP客户端.基本上,它使用函数fsockopen()连接到端口5060$fp fsockopen("10.0.0.1", 5060, $errno, $errstr, 30);然后基本上使用fread()和fwrite()读写SIP命令.现在,我的SIP服务操作符希望我们的客户使用SIPS,基本上是通过TLS的SIP.我花了…

简单的php探针,php探针程序的推荐

在我们之前的文章已经为大家介绍了什么是php探针&#xff0c;以及他的主要作用是什么&#xff0c;如果你接触了cms或许就会有点了解&#xff0c;当然&#xff0c;不要紧&#xff0c;看完这篇就知道php探针是做什么的了。php探针通常是用来探测空间、服务器运行的状况和php相关信…

php熊掌号怎么设置json-ld,dedecms织梦系统对接百度熊掌号并添加JSON_LD数据

百度近期推出的百度熊掌号非常的不错,我的dedecms织梦系统早早就对接好了,它能对你的原创文章进行原创保护,并评出熊掌号搜索指数,熊掌号搜索指数是对你文章的内容质量,用户喜爱、原创能力、活跃表现、领域专注五个维度进行计算评估而得到的。你的dedecms织梦网站开通熊掌号之后…

php获取信息,PHP文件信息获取函数

知识点&#xff1a;basename():获取文件名&#xff0c;传入第二个参数则只显示文件名&#xff0c;不显示后缀dirname():获取文件路径pathinfo():将文件信息存入一个数组&#xff0c;通过索引basename&#xff0c;dirname&#xff0c;extension可以获得对应的文件名&#xff0c;…

判断文件是否改变php,PHP判断文件是否被修改实例

在网站的管理系统中&#xff0c;有时需要查看某个文件是否被修改过、在什么时间被修改的、最后的修改时间是什么时候&#xff0c;本实例就可以实现这个功能&#xff0c;对表单中提交的文件进行判断&#xff0c;检测出修改时间。关键技术本实例主要应用filectime()和filemtime()…

java输入流转成输出流,[转]java 输出流转输入流

ByteArrayOutputStream.toByteArrayByteArrayInputStreamStringWriter.toStringStringReader字符流和二进制流是javaIO的两类流,输入流和输出流是javaIO的两类流如果你曾经使用过Java IO 编程&#xff0c;很可能会遇到这样一个状况&#xff0c;在一个类中向OutputStream里面写数…

matlab压控振荡器,MATLAB仿真应用_第5章(1)解析.ppt

第5章 数字通信系统的仿真(1) 5.1 概述 5.2 信源 5.3 信源编码 5.4 调制技术(模拟调制) 5.1 概述 实际的数字通信系统需要完成从信源到信宿的全部功能&#xff0c;这通常是比较复杂的。对这个系统做出的任何改动(如改变系统的结构、改变某个参数的设置等)都可能影响到整个系统的…

mysql pdo 查询一条数据,使用 PDO 关联查询 MySQL 数据

使用pdo关联查询mysql数据try {$pdo new PDO(mysql:hostlocalhost;dbnametest;, root, 123456);// 0.等值联结$sql SELECT c.name, o.id, o.customer_id, o.price FROM orders o, customer c WHERE o.customer_id c.id AND c.name :name;// 1.内联结(与上面等值联结返回的查…

php pdo 关闭,php pdo预处理

什么是预处理语句&#xff1f;可以把它看作是想要运行的 SQL 的一种编译过的模板&#xff0c;它可以使用变量参数进行定制。预处理语句可以带来两大好处&#xff1a;查询仅需解析(或预处理)一次&#xff0c;但可以用相同或不同的参数执行多次。当查询准备好后&#xff0c;数据库…

java 下载后删除,在服务器端生成文件后,下载后并删除,改了后发现文件变成空白解决思路...

当前位置:我的异常网 Java Web开发 在服务器端生成文件后,下载后并删除,改了后发现文件在服务器端生成文件后,下载后并删除,改了后发现文件变成空白解决思路www.myexceptions.net 网友分享于&#xff1a;2015-08-26 浏览&#xff1a;99次在服务器端生成文件后,下载后并删除,…