`
huangyongxing310
  • 浏览: 495830 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

base64与file 相互转换

 
阅读更多
base64与file 相互转换



import org.apache.commons.net.util.*;
import sun.misc.BASE64Decoder;


public static File base64ToFile(String base64, String path) {
        byte[] buffer;
        File file = new File(path);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
     
        	byte[] b = decoder.decodeBuffer(base64);
        	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 file;
        } catch (Exception e) {
            throw new RuntimeException("base64转换失败\n" + e.getMessage());
        }
    }
	
	/**
     * 文件转base64字符串
     * @param file
     * @return
     */
	//2-InputStream转化为base64
    public static String getBase64FromInputStream(InputStream in) {
        // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = in.read(buff, 0, 1024)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String str = new String(Base64.encodeBase64(data));
        //System.out.println( "str length: " + str.length() + "  str: " + str);
        return str;
    }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics