本文實例講述了Java實現文件和base64流的相互轉換功能。分享給大家供大家參考,具體如下:
import java.io.FileInputStream;import java.io.FileOutputStream;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;/** * 文件與base64的互相轉換操作*/public class testFile {public static void main(String[] args) {testFile t = new testFile();try {String ret = t.encodeBase64File("d://IE和火狐js或css差異.docx");System.err.println(ret);t.decoderBase64File(ret, "d://ghsTest/retFile.docx", "d://ghsTest/");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 將文件轉成base64 字符串* * @param path文件路徑* @return * * @throws Exception */ public static String encodeBase64File(String path) throws Exception { File file = new File(path); FileInputStream inputFile = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; inputFile.read(buffer); inputFile.close(); return new BASE64Encoder().encode(buffer); } /** * 將base64字符解碼保存文件* * @param base64Code * @param targetPath * @throws Exception */ public static void decoderBase64File(String base64Code, String targetPath,String catalogue) throws Exception { File file = new File(catalogue); if(file.exists()==false){ file.mkdirs(); } byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code); FileOutputStream out = new FileOutputStream(targetPath); out.write(buffer); out.close(); }}PS:這裡再推薦幾款加密解密相關在線工具供大家參考使用:
線編碼轉換工具(utf-8/utf-32/Punycode/Base64):
http://tools.VeVB.COm/transcoding/decode_encode_tool
BASE64編碼解碼工具:
http://tools.VeVB.COm/transcoding/base64
圖片轉換為Base64編碼在線工具:
http://tools.VeVB.COm/transcoding/img2base64
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.VeVB.COm/password/hash_md5_sha
更多關於java相關內容感興趣的讀者可查看本站專題:《Java數學運算技巧總結》、《Java數據結構與算法教程》、《Java字符與字符串操作技巧總結》、《Java操作DOM節點技巧總結》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。