------- 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('.'