首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

commons-codec-1.8施用Base64编解码

2013-08-01 
commons-codec-1.8使用Base64编解码package comimport java.io.Fileimport java.io.FileInputStreamimp

commons-codec-1.8使用Base64编解码

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);}}

热点排行