java实现字符串输出到本地文件,及base64生成图片到本地

/**
* base64字符串转换成图片
* imgStr base64字符串
* path 生成图片路径
* photoName 图片名称
*/
public static void createImage(String imgStr, String path,String photoName) {
BASE64Decoder decoder = new BASE64Decoder();
try {
String baseValue = imgStr.replaceAll(" ", "+");
byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
File file = new File(path);
File fileParent = file.getParentFile();//返回的是File类型,可以调用exsit()等方法
// 创建多级目录
if (!fileParent.exists()) {
fileParent.mkdirs();
}
//能创建文件
if (!file.exists()){
file.createNewFile();
}
OutputStream out = new FileOutputStream(path + "/" + photoName);
out.write(b);
out.flush();
out.close();

} catch (Exception e) {
log.info("保存图片失败: {}");
}
}

/**
* 保存字符串到本地文件
* str 要输出到文件中的字符串
* path 路径
*/
private static void writeStrToFile(String str, String path) throws IOException {
File file = new File(path);
File fileParent = file.getParentFile();//返回的是File类型,可以调用exsit()等方法
// 创建多级目录
if (!fileParent.exists()) {
fileParent.mkdirs();
}
//能创建文件
if (!file.exists()){
file.createNewFile();
}
Scanner input = new Scanner(str+"\n");
FileOutputStream fos = new FileOutputStream(path);
while (input.hasNext()) {
String a = input.next();
fos.write((a + "\r\n").getBytes());
}
fos.close();
input.close();
}

posted @ 2022-03-31 09:11  悄悄地超越  阅读(1264)  评论(0编辑  收藏  举报