1. Base64 加入 util包 (java.util.Base64)
在Java 8中,Base64编码已经成为Java类库的标准
Java 8 内置了 Base64 编码的编码器和解码器
Base64工具类提供了一套静态方法获取下面三种BASE64编解码器
基本:输出被映射到一组字符A-Za-z0-9+/,编码不添加任何行标,输出的解码仅支持A-Za-z0-9+/
URL:输出映射到一组字符A-Za-z0-9+_,输出是URL和文件
MIME:输出隐射到MIME友好格式。输出每行不超过76字符,并且使用’\r’并跟随’\n’作为分割。编码输出最后没有行分割
public class Java8Base64 {
public static void main(String args[]) throws Exception {
// base
String tempRaw = "java base64";
String tempTarget = Base64.getEncoder().encodeToString(tempRaw.getBytes("utf-8"));
System.out.println(tempRaw);
System.out.println(tempTarget);
System.out.println(new String(Base64.getDecoder().decode(tempTarget), "utf-8"));
// url
tempTarget = Base64.getUrlEncoder().encodeToString(tempRaw.getBytes("utf-8"));
System.out.println(tempTarget);
System.out.println(new String(Base64.getUrlDecoder().decode(tempTarget), "utf-8"));
// mime
tempTarget = Base64.getMimeEncoder().encodeToString(tempRaw.getBytes("utf-8"));
System.out.println(tempTarget);
System.out.println(new String(Base64.getMimeDecoder().decode(tempTarget), "utf-8"));
}
}
输出
java base64
amF2YSBiYXNlNjQ=
java base64
amF2YSBiYXNlNjQ=
java base64
amF2YSBiYXNlNjQ=
java base64
2. 带时区的 ZonedDateTime, LocalDateTime
public class Java8DateTime {
public static void main(String args[]) throws Exception {
ZonedDateTime shanghai = ZonedDateTime.parse("2019-01-01T01:01:01+08:00[Asia/Shanghai]");
System.out.println("shanghai");
System.out.println(shanghai);
System.out.println("tokyo");
System.out.println(ZoneId.of("Asia/Tokyo"));
System.out.println("system zone");
System.out.println(ZoneId.systemDefault());
System.out.println("time now");
System.out.println(LocalDateTime.now());
System.out.println("local date");
System.out.println(LocalDateTime.now().toLocalDate());
LocalDateTime localDateTime = LocalDateTime.now();
int year = localDateTime.getYear();
Month month = localDateTime.getMonth();
int day = localDateTime.getDayOfMonth();
System.out.println("year: " + year + ", month: " + month + ", day: " + day);
System.out.println("set time");
System.out.println(localDateTime.withDayOfMonth(1).withYear(2019));
System.out.println("set time");
System.out.println(LocalDate.of(2019, Month.JANUARY, 1));
System.out.println("set time");
// 解析字符串
System.out.println(LocalTime.parse("01:01:02"));
}
}
3. default method (默认实现方法)
public class Java8DefaultMethod {
public static void main(String args[]) {
Person chinese = new Chinese();
chinese.speak();
American american = new American();
american.speak();
}
}
interface Person {
default void speak() {
System.out.println("person speak");
}
}
class Chinese implements Person {
public void speak() {
System.out.println("chinese speak");
}
}
class American implements Person {
}
输出
chinese speak
person speak