1、JDK1.7
import sun.misc.BASE64Encoder;
import java.io.*;
import java.util.Objects;
public class Class01 {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("C:\\Users\\xxx\\Desktop\\abcdefg.mp3");
byte[] bytes = new byte[in.available()];
in.read(bytes);
in.close();
BASE64Encoder encoder = new BASE64Encoder();
String result = encoder.encode(Objects.requireNonNull(bytes));
File file = new File("C:\\Users\\xxx\\Desktop\\base64.txt");
FileOutputStream outputStream;
outputStream = new FileOutputStream(file);
outputStream.write(result.getBytes());
outputStream.close();
}
}
2、JDK1.8(JDK1.8前的 sun.misc.BASE64Encoder类产生的base64有自动换行现象,影响解析。JDK1.8的Base64类没有自动换行现象)
import java.io.*;
import java.util.Base64;
public class Class01 {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("C:\\Users\\xxxx\\Desktop\\abcdefg.mp3");
byte[] bytes = new byte[in.available()];
in.read(bytes);
byte[] encode = Base64.getEncoder().encode(bytes);
String result = new String(encode);
File file = new File("C:\\Users\\xxxx\\Desktop\\read02.txt");
FileOutputStream outputStream;
outputStream = new FileOutputStream(file);
outputStream.write(result.getBytes());
outputStream.close();
}
}
3、maven库 common-codec
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
import org.apache.commons.codec.binary.Base64;
import java.io.*;
public class Class01 {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("C:\\Users\\xxxx\\Desktop\\abcdefg.mp3");
byte[] bytes = new byte[in.available()];
in.read(bytes);
Base64 base64 = new Base64();
String s = base64.encodeToString(bytes);
File file = new File("C:\\Users\\xxxx\\Desktop\\read.txt");
FileOutputStream outputStream;
outputStream = new FileOutputStream(file);
outputStream.write(s.getBytes());
outputStream.close();
}
}