將文件轉(zhuǎn)成base64 字符串
將文件轉(zhuǎn)成base64 字符串,android 手機(jī)開發(fā)的時(shí)候會(huì)用到,,當(dāng)然在android有轉(zhuǎn)base64的方法,這里調(diào)用的是jdk的api
04 |
import java.io.FileInputStream; |
05 |
import java.io.FileOutputStream; |
07 |
import sun.misc.BASE64Decoder; |
08 |
import sun.misc.BASE64Encoder; |
10 |
public class File2Code { |
13 |
* <p>將文件轉(zhuǎn)成base64 字符串</p> |
18 |
public static String encodeBase64File(String path) throws Exception { |
19 |
File file = new File(path); |
20 |
FileInputStream inputFile = new FileInputStream(file); |
21 |
byte [] buffer = new byte [( int )file.length()]; |
22 |
inputFile.read(buffer); |
24 |
return new BASE64Encoder().encode(buffer); |
27 |
* <p>將base64字符解碼保存文件</p> |
32 |
public static void decoderBase64File(String base64Code,String targetPath) throws Exception { |
33 |
byte [] buffer = new BASE64Decoder().decodeBuffer(base64Code); |
34 |
FileOutputStream out = new FileOutputStream(targetPath); |
39 |
* <p>將base64字符保存文本文件</p> |
44 |
public static void toFile(String base64Code,String targetPath) throws Exception { |
45 |
byte [] buffer = base64Code.getBytes(); |
46 |
FileOutputStream out = new FileOutputStream(targetPath); |
50 |
public static void main(String[] args) { |
52 |
String base64Code =encodeBase64File( "D:\\1.jpg" ); |
53 |
System.out.println(base64Code); |
54 |
decoderBase64File(base64Code, "D:\\2.jpg" ); |
55 |
toFile(base64Code, "D:\\three.txt" ); |
56 |
} catch (Exception e) { |
|