1. 程式人生 > >檔案流轉換為base64碼 和 base64碼轉換為檔案流

檔案流轉換為base64碼 和 base64碼轉換為檔案流

package test.com.cs;

import com.cs.Base64Convert;
import junit.framework.TestCase;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Logger;

public class TestBase64Convert extends TestCase {
Base64Convert baseCov = null;

    public TestBase64Convert(String s) {
        super(s);

    }

    protected void setUp() throws Exception {
        baseCov = new Base64Convert();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testIoToBase64() {
        try {
String strBase64 = baseCov.ioToBase64(); //將 io 轉換為 base64編碼
            System.out.println(">>> "+strBase64);

baseCov.base64ToIo(strBase64); //將 base64編碼轉換為 io 檔案流,生成一幅新圖片
        } catch (FileNotFoundException e) {
            e.printStackTrace(); 
        } catch (IOException e) {
            e.printStackTrace(); 
        }
    }
}

------------------------------------

package com.cs;

import sun.misc.BASE64Decoder;
import sun.misc.
BASE64Encoder;

import java.io.*;

public class Base64Convert {
BASE64Decoder decoder = new BASE64Decoder();

    public String ioToBase64() throws IOException {
        String fileName = "d:/gril.gif"; //原始檔
        String strBase64 = null;
        try {
            InputStream in = new FileInputStream(fileName);
// in.available()返回檔案的位元組長度
            byte[] bytes = new byte[in.available()];
 // 將檔案中的內容讀入到陣列中
            in.read(bytes);
            strBase64 = new BASE64Encoder().encode(bytes);      //將位元組流陣列轉換為字串
            in.close();
        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return strBase64;
    }

    public void base64ToIo(String strBase64) throws IOException {
        String string = strBase64;
        String fileName = "d:/gril2.gif"; //生成的新檔案
        try {
 // 解碼,然後將位元組轉換為檔案
            byte[] bytes = new BASE64Decoder().decodeBuffer(string);   //將字串轉換為byte陣列
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            FileOutputStream out = new FileOutputStream(fileName);
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread); //檔案寫操作
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
執行截圖:gril2.gif就是根據base64編碼轉換過來的,看到谷歌的這個美女總裁,就說明你的程式成功了