Java,获取⽂件的Base64字符串,解码Base64字符串还原⽂件在jdk1.8以前,获取⽂件Base64字符串需要⽤到第三⽅库,从1.8开始,Java中引⼊了Base64相关的类
以下是代码⽰例
获取⽂件的Base64编码字符串
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Base64Encoder {
private static final Logger LOGGER = Logger("Base64Encoder");
public static void main(String[] args) {
System.out.print("Enter an input filename: ");
Scanner inputFromConsole = new Scanner(System.in);
String filename = Line();
FileOutputStream outputToFile = null;
try (FileInputStream inputFromFile = new FileInputStream(filename)) {
System.out.print("Enter an encoded filename: ");
filename = Line();
outputToFile = new FileOutputStream(filename);
byte[] src = new byte[inputFromFile.available()];
byte[] encodedBytes = Encoder().encode(src);
outputToFile.write(encodedBytes);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} finally {
if (outputToFile != null) {
try {
outputToFile.close();
} catch (IOException ex) {
inputtypefile样式LOGGER.log(Level.SEVERE, null, ex);
}
}
}
}
}
解码Base64字符串还原⽂件
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Base64Decoder {
private static final Logger LOGGER = Logger("Base64Decoder");
public static void main(String[] args) {
if (args.length == 2) {
try (FileInputStream encoded = new FileInputStream(args[0]); FileOutputStream decoded = new FileOutputStream(args[1])) {
byte[] buffer = new byte[encoded.available()];
Base64.Decoder base64Decoder = MimeDecoder();
decoded.write(base64Decoder.decode(buffer));
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
} else {
out.println("usage:\n\tjava Base64Decoder <encoded filename> <decoded filename>");
out.println("for example:\n\tjava Base64Decoder MyPic.jpg");
}
} }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论