这里用到的主要工具类是import java.util.Base64;(存在于java8及跟高版本)
第一步:扫描文件夹,获取文件名
如果是单个文件解析,这步可以省略,直接用代解析的内容解析。
/**
* 读取文件夹下的所有文件名
* @param path 文件夹所在路径
* @return 文件名列表
*/
public static List<File> readFiles(String path){
File root = new File(path);
List<File> files = new ArrayList<File>();
if(!root.isDirectory()){
files.add(root);
}else{
File[] subFiles = root.listFiles();
for(File f : subFiles){
files.addAll(readFiles(f.getAbsolutePath()));
}
}
return files;
}
第二步:解码并保存图片
/**
* 图片解码
* @param imgStr 待解码数据
* @param path 解码完成后文件保存路径
* @return
*/
public static boolean getDecoderBase64(String imgStr,String path){
if (imgStr == null){
return false;
}
//截取data:image/png;base64,iVB...需要解析的数据
String imgStrArray[] = imgStr.split(",");
imgStr = imgStrArray[1];
Decoder decoder = Base64.getDecoder();
try{
byte[] b = decoder.decode(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
//输出保存图片
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
}catch (Exception e) {
return false;
}
}
测试用例
public static void main(String[] args) {
//String strImg = "data:image/png;base64,iVBORA...K5CYII=";
String path = "E:/images/stop_card/37/";//文件路径
List<File> files = readFiles(path);
// 遍历文件并处理
for (File ele : files) {
// 处理文件
String filename = ele.getName();//文件名
//指定特定的处理后缀名,防止文件读取出错
if(".jsp".equals(filename.substring(filename.length()-4))){
File filepath=new File(path + filename);
System.out.println(filename);
try {
if(!filepath.exists()||filepath.isDirectory()){
throw new FileNotFoundException();
}
FileInputStream fin=new FileInputStream(filepath);
//创建字节数组,准备将文件流中的数据传给字节数组
byte[] b=new byte[fin.available()];
//将字节流中的数据传递给字节数组
fin.read(b);
//将字节数组转为字符串
String strImg=new String(b);
System.out.println("保存数据:"+strImg);
fin.close();
String savepath = path + filename.substring(0,filename.length()-4)+".png";
getDecoderBase64(strImg, savepath);
System.out.println("***********结束************");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}