package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
public class R {
public static void main(String[] args) throws Exception {
Base64WithImage t = new Base64WithImage();
t.process();
}
public static Exception test() throws Exception {
try {
throw new IOException();
} catch (IOException e) {
System.out.println("cath");
return new Exception();
} finally {
System.out.println("final");
}
}
}
class Base64WithImage {
public static String TXT = "E:/test.txt";
public static String IMAGE = "E:/test_copy.png";
public static byte[] data;
public static String content;
public Base64WithImage() throws IOException {
File file = new File(IMAGE);
FileInputStream in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
}
public String image2Base64() throws IOException {
/*
* Base64 encoder = new Base64(); data = encoder.encode(data);
*/
data = Base64.encodeBase64(data);
System.out.println(data);
StringBuffer sb = new StringBuffer();
for (byte bt : data) {
sb.append((char) bt);
}
content = sb.toString();
return sb.toString();
}
public void writeBase642TXT() throws IOException {
File file = new File(TXT);
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
}
public void Base642Image() throws IOException {
byte[] da = Base64.decodeBase64(content);
FileOutputStream fos = null;
try {
File file = new File(TXT);
fos = new FileOutputStream(file);
fos.write(da);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
fos.close();
}
}
public String readTXT() throws IOException {
File file = new File(TXT);
FileInputStream fis = new FileInputStream(file);
System.out.println(fis.available());
byte[] c = new byte[fis.available()];
fis.read(c);
fis.close();
System.out.println(new String(c));
return new String(c);
}
public void writeImage(byte[] data) throws IOException {
File file = new File("E:/tt.png");
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
}
public void process() throws IOException {
image2Base64();
writeBase642TXT();
String c = readTXT();
byte[] da = Base64.decodeBase64(c);
writeImage(da);
}
}
commons-codec-1.8使用Base64编解码
最新推荐文章于 2021-08-30 10:38:24 发布