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();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM