Java實現(xiàn)文件和base64流的相互轉(zhuǎn)換功能示例
本文實例講述了Java實現(xiàn)文件和base64流的相互轉(zhuǎn)換功能。分享給大家供大家參考,具體如下:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* 文件與base64的互相轉(zhuǎn)換操作
*/
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 block
e.printStackTrace();
}
}
/**
* 將文件轉(zhuǎn)成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:這里再推薦幾款加密解密相關(guān)在線工具供大家參考使用:
線編碼轉(zhuǎn)換工具(utf-8/utf-32/Punycode/Base64):
http://tools.jb51.net/transcoding/decode_encode_tool
BASE64編碼解碼工具:
http://tools.jb51.net/transcoding/base64
圖片轉(zhuǎn)換為Base64編碼在線工具:
http://tools.jb51.net/transcoding/img2base64
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)學運算技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java字符與字符串操作技巧總結(jié)》、《Java操作DOM節(jié)點技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
利用synchronized實現(xiàn)線程同步的案例講解
這篇文章主要介紹了利用synchronized實現(xiàn)線程同步的案例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
java編程隊列數(shù)據(jù)結(jié)構(gòu)代碼示例
這篇文章主要介紹了java編程隊列數(shù)據(jù)結(jié)構(gòu)代碼示例,簡單介紹了隊列的相關(guān)基礎(chǔ)知識,然后通過實例向大家展示其實現(xiàn)方法,具有一定參考價值,需要的朋友可以了解下。2017-11-11
詳解Java獲取環(huán)境變量及系統(tǒng)屬性的方法
這篇文章主要介紹了詳解Java獲取環(huán)境變量及系統(tǒng)屬性的方法,講解了System.getEnv()和System.getProperties()這兩個核心方法的使用,需要的朋友可以參考下2016-05-05
springboot整合mybatis實現(xiàn)多表查詢的實戰(zhàn)記錄
SpringBoot對數(shù)據(jù)庫操作有多種方式,下面這篇文章主要給大家介紹了關(guān)于springboot整合mybatis實現(xiàn)多表查詢的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細,需要的朋友可以參考下2021-08-08

