记一个flag工具类
需求是定时任务执行防止发生重复等问题,所以需要定义一个flag,在每次执行任务前根据flag进行判断,及执行任务后对flag进行重新赋值。
文本内容如下:
代码如下:主要方法为getMapFromText,MapToText
public static String readTxt(String txtPath) {
File file = new File(txtPath);
if(file.isFile() && file.exists()){
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer();
String text = null;
while((text = bufferedReader.readLine()) != null){
sb.append(text);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
/**使用FileOutputStream来写入txt文件
* @param txtPath txt文件路径
* @param content 需要写入的文本
*/
public static void writeTxt(String txtPath,String content){
FileOutputStream fileOutputStream = null;
File file = new File(txtPath);
try {
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
if(file.exists()){
//判断文件是否存在,如果不存在就新建一个txt
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Author Chen
* @Description //TODO 把txt的路径传入,返回一个map;
* @Date 2019/12/6
* @Param [textPath]
* @return java.util.Map<java.lang.String,java.lang.String>
**/
public static Map<String,String> getMapFromText(String textPath){
Map<String, String> map = new HashMap<>();
String flag=FileTxtUtil.readTxt(textPath);
String[] split = flag.split(";");
for (String str:split){
if (!StringUtils.isBlank(str)){
String[] splitOne = str.split(":");
map.put(splitOne[0],splitOne[1]);
}
}
return map;
}
/**
* @Author Chen
* @Description //TODO 传入一个map,及txt文件的路径,将map写入到文件中去,若文件不存在,会生成文件
* @Date 2019/12/6
* @Param [flagMap, path]
* @return void
**/
public static void MapToText(Map<String,String> flagMap,String path){
String str="";
for(String key:flagMap.keySet()){
str+=key+":"+flagMap.get(key)+";\r\n";
}
FileTxtUtil.writeTxt(path,str);
}