文件内容:text.txt
{"name":"利威尔","number":"abc123"}
主类:
package practiceDemo1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class TestFile01 {
public static void main(String[] args) {
String fileContent = encodeBase64File("E://text.txt");
System.out.println("base64编码:");
System.out.println(fileContent);
byte[] buffer = new byte[(int) fileContent.length()];
String str = "";
try {
buffer = Base64.getDecoder().decode(fileContent); //base64编码转为byte[]
str = new String(buffer,"gb2312"); //byte[]转为String
}catch(Exception e) {
}
System.out.println("文件原内容:");
System.out.println(str);
}
//读取文件,将文件内容转为base64编码
public static String encodeBase64File(String path) {
File file = new File(path);
FileInputStream inputFile;
byte[] buffer = null;
try {
inputFile = new FileInputStream(file);
buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Base64.getEncoder().encodeToString(buffer);
}
}
运行结果:
base64编码:
eyJuYW1lIjoiwPvN/rb7IiwibnVtYmVyIjoiYWJjMTIzIn0=
文件原内容:
{"name":"利威尔","number":"abc123"}