jdk1.8——Base64

x33g5p2x  于2022-01-13 转载在 其他  
字(2.8k)|赞(0)|评价(0)|浏览(402)

jdk1.8新增了Base64编解码功能;

提供了3种Base64编码方式:

  1. Basic:Base64.getEncoder()和Base64.getDecoder()

编码输出组成:大小写字母、数字、+、/

如果编码后的二进制长度非3的倍数则会使用=补齐,所以编码后会有0-2个=在结尾,不需要补齐可以使用Base64.getEncoder().withoutPadding();(下同)

  1. URL and Filename safe:Base64.getUrlEncoder()和Base64.getUrlDecoder()

编码输出组成:大小写字母、数字、-、_

编码后不包含“/”等特殊字符,不会对url或者文件名或者路径造成干扰;

  1. MIME:Base64.getMimeEncoder()、Base64.getMimeEncoder(lineLength, lineSeparator)和Base64.getMimeDecoder()

编码输出组成跟Basic一样,不过限制了每行的长度和每行的分隔符,默认的每行不超过76个字符并且用\r\n作为换行符,也可以自定义行长度和行分隔符;

指定行长的时候会四舍五入到4的倍数长度(向下取到4的倍数的长度,如果长度<=0则不会分行);

指定的分隔符不能包含编码表里的字符(不能包含Basic里的:大小写字母、数字、+、/,但是可以包含-和_);

Encoder可以使用的编码方法:

Decoder可以使用的解码方法:

小Demo:

@Test
	public void test() {
		System.out.println("========1=======");
		Encoder baseEncoder = Base64.getEncoder();
		Decoder baseDecoder = Base64.getDecoder();
		String s1 = baseEncoder.encodeToString("12345678?abcd".getBytes());
		System.out.println(s1);
		byte[] bytes1 = baseDecoder.decode(s1);
		System.out.println(new String(bytes1));
		
		System.out.println("========2=======");
		Encoder urlEncoder = Base64.getUrlEncoder();
		Decoder urlDecoder = Base64.getUrlDecoder();
		String s2 = urlEncoder.encodeToString("12345678/abcde".getBytes());
		System.out.println(s2);
		byte[] bytes2 = urlDecoder.decode(s2);
		System.out.println(new String(bytes2));
		
		System.out.println("========3=======");
		Encoder mimeEncoder = Base64.getMimeEncoder();
		Decoder mimeDecoder = Base64.getMimeDecoder();
		String s3 = mimeEncoder.encodeToString("123abc测试123abc测试123abc测试123abc测试123abc测试123abc测试".getBytes());
		System.out.println(s3);
		byte[] bytes3 = mimeDecoder.decode(s3);
		System.out.println(new String(bytes3));
		
		System.out.println("========4=======");
		Encoder mimeEncoder4 = Base64.getMimeEncoder(4, "~".getBytes());
		Encoder mimeEncoder5 = Base64.getMimeEncoder(5, "~".getBytes());
		Encoder mimeEncoder6 = Base64.getMimeEncoder(6, "~".getBytes());
		Encoder mimeEncoder7 = Base64.getMimeEncoder(7, "~".getBytes());
		Encoder mimeEncoder8 = Base64.getMimeEncoder(8, "_".getBytes());
		Encoder mimeEncoder9 = Base64.getMimeEncoder(9, "_".getBytes());
		Encoder mimeEncoder10 = Base64.getMimeEncoder(10, "_".getBytes());
		System.out.println(mimeEncoder4.encodeToString("aaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
		System.out.println(mimeEncoder5.encodeToString("aaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
		System.out.println(mimeEncoder6.encodeToString("aaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
		System.out.println(mimeEncoder7.encodeToString("aaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
		System.out.println(mimeEncoder8.encodeToString("aaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
		System.out.println(mimeEncoder9.encodeToString("aaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
		System.out.println(mimeEncoder10.encodeToString("aaaaaaaaaaaaaaaaaaaaaaa".getBytes()));
	}

输出:

相关文章