commons-codec-1.8使用Base64编解码

本文介绍了一个Java程序,该程序能够将图片文件转换为Base64编码,并将编码后的字符串写入文本文件中,再从文本文件读取Base64编码并还原成图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值