File转化为Base64,主要用于图片传输。
1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import sun.misc.BASE64Encoder;
6
7 public class Base64Util {
8
9 /**
10 * 将文件转化为Base64字符串
11 * @param file
12 * @return
13 */
14 public static String getFileBase64(File file){
15 InputStream in = null;
16 byte[] data = null;
17 try{
18 in = new FileInputStream(file);
19 data = new byte[in.available()];
20 in.read(data);
21 }catch (IOException e){
22 e.printStackTrace();
23 }finally {
24 if (in != null) {
25 try { in.close(); } catch (IOException e) { e.printStackTrace(); }
26 }
28 }
29 //Base64编码
30 BASE64Encoder encoder = new BASE64Encoder();
31 return encoder.encode(data);
32 }
3340 }