try-with-resources
JDK7新增的处理方式,是为资源关闭设置的语法
try(需要关闭的资源对象(任何实现java.lang.AutoClosable或java.io.Closable的对象))
{
可能发生异常的逻辑代码
}
catch(异常类型 e)
{
异常处理代码
}
catch(异常类型 e)
{
异常处理代码
}
关闭资源和final的执行顺序:在try-with-resource语句中,任何catch或finally块在声明的资源关闭后运行
Java中需要调用close()方法手动关闭的资源:类似于InputStream,OutputStream,Scanner,PrintWtiter的资源,一般通过try-catch-finally实现,例如:
public class K
{
public static void main(String[] args)
{
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try
{
fileInputStream = new FileInputStream("src/a.txt");
fileOutputStream = new FileOutputStream("src/b.txt");
byte[] bytes = new byte[1024];
int b;
while(-1!=(b=fileInputStream.read(bytes)))
{
fileOutputStream.write(bytes);
}
fileOutputStream.flush();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
用try-with-resources代替
public class J
{
public static void main(String[] args)
{
try(FileInputStream fileInputStream = new FileInputStream("src/a.txt");
FileOutputStream fileOutputStream = new FileOutputStream("src/b.txt")
)
{
byte[] b = new byte[1024];
int i;
while(-1!=(i=fileInputStream.read(b)))
{
fileOutputStream.write(b);
}
fileOutputStream.flush();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
面对必须要关闭的资源,我们总是应该优先用try-with-resources,而不是try-catch-finally,其产生的代码更简短,更清晰,产生的异常对我们更有用,try-with-resources语句让我们更容易编写必须要关闭的资源的代码,若采用try-finally基本做不到这点