FileIOUtils.java
package com.vcredit.ddcash.batch.util;
import com.vcredit.ddcash.batch.autoAdvance.AutoAdvanceTask;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import java.io.*;
/**
* 操作文件工具类
* Created by xutao on 2016/11/9 0009.
*/
public class FileIOUtils {
private static final Logger LOGGER = Logger.getLogger(FileIOUtils.class);
/**
* 保存内容到指定的路径的文件中,根据分隔符换行
*
* @param targetFolder 指定的文件路径
* @param fileName 指定的文件名
* @param saveContent 待保存的内容
*/
public static void saveStringArray2File(File targetFolder, String fileName, String saveContent, String delimiter) {
if (targetFolder == null
|| StringUtils.isBlank(fileName)
|| StringUtils.isEmpty(saveContent)
|| StringUtils.isBlank(delimiter)) {
throw new RuntimeException("请求参数不正确->不能为空");
}
BufferedWriter writer = null;
try {
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
File targetFile = new File(targetFolder, fileName);
if (!targetFile.exists()) {
targetFile.createNewFile();
}
LOGGER.info("开始写入到文件,参数->路径名->" + targetFolder.getPath() + "->文件名->" + fileName + "->保存内容->" + saveContent + "->分隔符->" + delimiter);
writer = new BufferedWriter(new FileWriter(new File(targetFolder, fileName), true));
String[] contentArr = saveContent.split(delimiter);
for (String str : contentArr) {
writer.write(str, 0, str.length());
writer.newLine();
}
writer.flush();
} catch (Exception e) {
LOGGER.error("写入字符串到文件失败", e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
LOGGER.error("关闭IO流失败");
}
}
}
}
}