通过base64字符串把音频文件(mp3)保存到本地的绝对路径
/*** 获得 base64 字符串的音频文件* @return*/public String base64() {String url = "D:" + File.separator + "date" + File.separator ;String base64Code = null;try {System.out.println(url + "13066.mp3");bas
·
/**
* 获得 base64 字符串的音频文件
* @return
*/
public String base64() {
String url = "D:" + File.separator + "date" + File.separator ;
String base64Code = null;
try {
System.out.println(url + "13066.mp3");
base64Code = base64Config.encodeBase64File(url+ "13066.mp3");
} catch (Exception e) {
e.printStackTrace();
System.out.println("转base64字符串失败");
}
return base64Code;
}
/**
* @param base64 字符串
* @param fileName 文件名
* @param savePath 保存路径
*/
public static void base64ToFile(String base64, String fileName, String savePath) {
File file = null;
//创建文件目录
String filePath = savePath;
File dir = new File(filePath);
//判断是否存在文件夹
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdirs();
}
BufferedOutputStream bos = null;
java.io.FileOutputStream fos = null;
try {
byte[] bytes = Base64.getMimeDecoder().decode(base64);
file=new File(filePath + fileName);
fos = new java.io.FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//按年月格式把数据分开保存
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH )+1;
String months = month <10 ? "0" + month : month + "";
String url = "D:" + File.separator + "date" + File.separator + year + "_" + months + File.separator;
String base64 = this.base64();
base64ToFile(base64,"xxx.mp3",url);
public class base64Config {
/**
* <p>将文件转成base64 字符串</p>
* @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);
}
/**
* <p>将base64字符解码保存文件</p>
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void decoderBase64File(String base64Code,String targetPath) throws Exception {
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
/**
* <p>将base64字符保存文本文件</p>
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static void toFile(String base64Code,String targetPath) throws Exception {
byte[] buffer = base64Code.getBytes();
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)