import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;jsp
/**
* Created by Administrator on 2017/10/28 0028.
*/
public class FileUtil {
public static final String DEPATH = "D:/test/deFile/test.jsp";
public static final String ENPATH = "D:/test/enFile/test.jsp";
public static final String PATH = "D:/test/File/test.jsp";
/**
* 將文件轉成base64字符串
* @param path 文件路徑
* @return String
* @throws Exception
* */
public static String encodeBase64File(String path)throws Exception{
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
//是否read讀入的數據交給buffer
fileInputStream.read(buffer);
fileInputStream.close();
return new BASE64Encoder().encode(buffer);
}
/**
* 將文件base64字符解碼並保存到目標文件
* @param base64Code 字符串 targetPath 目標文件
* @return void
* @throws Exception
* */
public static void decoderBase64File(String base64Code,String targetPath)throws Exception{
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream fileOutputStream = new FileOutputStream(targetPath);
fileOutputStream.write(buffer);
fileOutputStream.close();
}
/**
* 將文件base64字符保存文件
* @param base64Code 字符串 targetPath 目標文件
* @return void
* @throws Exception
* */
public static void base64ToFile(String base64Code,String targetPath)throws Exception{
byte[] buffer = base64Code.getBytes();
FileOutputStream fileOutputStream = new FileOutputStream(targetPath);
fileOutputStream.write(buffer);
fileOutputStream.close();
}
public static void main(String[] agrs){
try {
String base64Code = encodeBase64File(ENPATH);
System.out.println(base64Code);
decoderBase64File(base64Code,DEPATH);
base64ToFile(base64Code,PATH);
}catch (Exception e){
e.printStackTrace();
}
}
}
注:僅供分享,內容參照其餘學者.net