JDK7新特性

JDK7新特性

1.二进制字面量

JDK7开始,终于可以用二进制来表示整数(byte,short,int和long)。
使用二进制字面量的好处是,可以使代码更容易被理解。语法非常简单,只要在二进制数值前面加 0b或者0B例如:int x = 0b110110

2.数字字面量

为了增强对数值的阅读性,如我们经常把数据用逗号分隔一样。JDK7提供了_对数据分隔。举例:int x = 100_1000;

注意事项:

  1. 不能出现在进制标识和数值之间
  2. 不能出现在数值开头和结尾
  3. 不能出现在小数点旁边

switch中可以使用字串了


switch (""){
    case "":
        break;
                

try-with-resources

操作的类****只要是实现了AutoCloseable接口就可以在try语句块退出的时候自动调用close方法关闭流资源****。

  • 原来
InputStream is = null;
OutputStream os = null;
try {
    // 流
    is = xxx;
    os = xxx;
    //use
    is.read();
    os.write();
} finally {
    // close
    if(stream != null){
        try{
            is.close();
        }catch(Exeception e){
            //xxx
        }
        try{
            os.close();
        }catch(Exeception e){
            //xxx
        }
    }
}
  • 现在

try ( InputStream is  = new FileInputStream("xx");
      OutputStream os = new FileOutputStream("xx")
) {
    //xxx
    //不用关闭了,JVM帮你关闭流
}

常用于流对象,连接池等的自动关闭。

如果自己的类,实现AutoCloseable,实现其close方法,即可使用。

NIO2文件 Files

读取写入
  
public final class Files {}

img

//读取字节
byte[] dataBytes = Files.readAllBytes(Paths.get("D:\\xxx"));
//readline
List<String> lines = Files.readAllLines(Paths.get("D:\\xxx"));

lines.forEach(v-> System.out.println(v));
 

写入方法

img

//写入文件
Files.write(Paths.get("D:\\xxx"), "xxx".getBytes());
//指定模式写入,比如追加
Files.write(Paths.get("D:\\xxx"), "xxx".getBytes(), StandardOpenOption.APPEND);
 
/****默认UTF-8编码,可以手工指定******/
构造流模式
InputStream is = Files.newInputStream(path);
OutputStream os = Files.newOutputStream(path);
 
Reader reader = Files.newBufferedReader(path);
Writer writer = Files.newBufferedWriter(path);
操作目录
//判断存在
Files.exists(path);
//
Files.createFile(path);
//
Files.createDirectory(path);
//文件列表,可以流运算遍历
Stream<Path> list(Path dir)
//文件列表
Stream<Path> walk(Path start, FileVisitOption... options)
 
Files.copy(in, path);
Files.move(path, path);
Files.delete(path);
 
 
//创建临时文件、临时目录:
Files.createTempFile(dir, prefix, suffix);
Files.createTempFile(prefix, suffix);
Files.createTempDirectory(dir, prefix);
Files.createTempDirectory(prefix);
Path对象
Path path = Paths.get("xxx", "name");
Path path = Paths.get("xxx/name");
 
Path path = Paths.get(URI.create("xxx路径"));
 
Path path  = new File("xxx").toPath();
Path path = FileSystems.getDefault().getPath("xxx");
 
//Path、URI、File之间的转换
File file = new File("xxx");
Path path = file.toPath();
File file = p1.toFile();
URI uri = file.toURI();

多异常统一处理


try {
    //xxx
} catch (AException e) {
    e.printStackTrace();
} catch (BException e) {
    e.printStackTrace();
}

try {
    //xxx
} catch (AException | BException e) {
    e.printStackTrace();
}

反应推导


List<String> list = new ArrayList<>();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值