base64文件转字符串

  • A+
所属分类:Java
import java.io.*;
/**
 * 如果是图片转换,可以加上:data:image/png;base64,
 */
public class Base64Util {
    public static String fileToBase64(String path) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64();
        return new String(encoder.encode(data));
    }
    public static boolean Base64Tofile(String base64str, String path) {
        if (base64str == null)
            return false;
        try {
            byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(base64str);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: