Java 12 它不是一个长久支持(LTS)版本。
重点特性列表:
- Switch 表达式(预览特性)
- 文件对比增强
Switch 表达式(预览特性)
在 Java 12 中,对 Switch 表达式的写法进行了改进,虽然是一个语法糖的改进,也让 Switch 的代码编写变得更加优雅,如再Java12之前的switch:
String day = "march";
switch (day) {
case "march":
case "april":
case "may":
System.out.println("春天");
break;
case "june":
case "july":
case "august":
System.out.println("夏天");
break;
case "september":
case "october":
case "november":
System.out.println("秋天");
break;
case "december":
case "january":
case "february":
System.out.println("冬天");
break;
}
Java12or14
现在可以改为如下写法:
String day = "march";
switch (day) {
case "march", "april", "may" -> System.out.println("春天");
case "june", "july", "august" -> System.out.println("夏天");
case "september", "october", "november" -> System.out.println("秋天");
case "december", "january", "february" -> System.out.println("冬天");
}
以及在表达式返回值,像下面这样:
String day = "march";
String data = switch (day) {
case "march", "april", "may" -> "春天";
case "june", "july", "august" -> "夏天";
case "september", "october", "november" -> "秋天";
case "december", "january", "february" -> "冬天";
default -> "dayError";
};
System.out.println("当前季节是:" + data);
文件对比增强-Files.mismatch
在 Java 中对于文件的操作已经在 Java 7 中进行了一次增强,这次 Java 12 又带来了文件对比功能。对比两个文件,如果内容一致,会返回 -1 ,如果内容不同,会返回不同的字节开始位置。
// 创建两个文件
Path pathA = Files.createFile(Paths.get("glj1.txt"));
Path pathB = Files.createFile(Paths.get("glj2.txt"));
// 写入相同内容
Files.write(pathA,"abc".getBytes(), StandardOpenOption.WRITE);
Files.write(pathB,"abc".getBytes(), StandardOpenOption.WRITE);
long mismatch = Files.mismatch(pathA, pathB);
System.out.println(mismatch);
// 追加不同内容
Files.write(pathA,"123".getBytes(), StandardOpenOption.APPEND);
Files.write(pathB,"321".getBytes(), StandardOpenOption.APPEND);
mismatch = Files.mismatch(pathA, pathB);
System.out.println(mismatch);
// 删除创建的文件
pathA.toFile().deleteOnExit();
pathB.toFile().deleteOnExit();