save Base64 String To File - Android File Input Output

Android examples for File Input Output:Base64

Description

save Base64 String To File

Demo Code


//package com.java2s;
import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.util.Base64;

public class Main {
    /**/*from  w  w  w .j  av  a 2  s. co m*/
     * Base64 to File
     * @param base64Str
     * @param filePath
     * @param fileName
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveBase64StringToFile(String base64Str,
            String filePath, String fileName) throws FileNotFoundException,
            IOException {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath, fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            byte[] bfile = Base64.decode(base64Str, Base64.DEFAULT);
            bos.write(bfile);
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

Related Tutorials