jdk7更新-语言增强

340 阅读1分钟

可以在switch语句的表达式中使用String对象:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

The try-with-resources Statement

该try-with资源语句是try声明了一个或多个资源声明。一个资源是一个对象的程序与它完成后,必须关闭。该try-with资源语句确保每个资源在发言结束时关闭。任何实现的对象(java.lang.AutoCloseable包括所有实现的对象)java.io.Closeable都可以用作资源。

下面的示例从文件中读取第一行。它使用的实例BufferedReader从文件中读取数据。BufferedReader是必须在程序完成后关闭的资源:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

请注意, 1、资源的close方法的调用顺序与它们的创建顺序相反。 2、try-with-resources语句可以具有catch and finally块,就像普通try语句一样。在try-with-resources语句中,任何catch或finally块在声明的资源关闭后运行。 3、当关闭with释放资源时,抛出的异常刚好是整个方法抛出的异常,可以通过Throwable.getSuppressed方法来获取抛出的异常