黑马程序员————JDK1.7/1.8新特性详解

本文讲解了JDK1.7和1.8的一些常见新特性,例如JDK1.7新添加的try-resource语句实现对资源的自动关闭,和还有对文件相关的一些操作。JDK 1.8最显著的新特性莫过于lambda函数式接口,和JavaFX。
摘要由CSDN通过智能技术生成

        ------- Android培训Java培训、期待与您交流!-------

                          


                            一.JDK 1.7新特性        

1.1 异常处理改进

   try-with-resources语句

public class Test {
	public static void main(String[] args) {
		try(FileInputStream fin=new FileInputStream("res.txt"))//放在这其中的资源必须继承AutoCloseable才可以
		{
		int x;
		while((x=fin.read())!=-1)
		{
		System.out.print((char)x);	
		}} 
		catch (IOException e) {e.printStackTrace();}}}

  捕获多个异常

try
 {
	 
 }
 catch(A|B|C ex)
 {
	 
 }
 //只有当A,B,C没有继承关系时才可以,A,B,C默认是常量。

public class Test {
	public Test(int x) throws A, B
	{
    if(x==0)
	throw  new A("异常A");
    else
    	throw  new B("异常B");
	
	}
	public static void main(String[] args) {
	  
     try {
		Test t=new Test(2);
	} catch (A |B e) {
	   e.printStackTrace();
	}  
	}
	}

 
class A extends Exception
{
public A(String str)
{
System.out.println(str);
}
}
class B extends Exception
{
public B(String str)
{
System.out.println(str);
}
}

 使反射方法的异常处理简单化

 在反射方法的方法中可能抛出多个异常,当然你可以使用捕获多个异常的方法,但是还有一种更简单的方法是JDK1.7为次提供了一个新的父类异常接口:ReflectiveOperationException。

1.2 使用文件的改进

     Path

public class Test {
 
	public static void main(String[] args) throws IOException {
		String fileSource="in.txt";
		String fileTo =null;
		String path=System.getProperty("user.dir");
		File dir=Paths.get(path).toFile();
		File[] file=dir.listFiles();
		for(File f:file)
		{ 
		 if(f.getName().equalsIgnoreCase(fileSource)){
		fileTo=fileSource.substring(0, fileSource.lastIndexOf('.'))+"-副本"+(int)(Math.random()*9+1)+fileSource.substring(fileSource.lastIndexOf('.'
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值