package com.digiccy.publish;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import com.digiccy.publish.common.JsonUtil;
import com.digiccy.publish.dao.dto.ZHDto;
public class FileUtils {
private static void getFiles(File dir) throws IOException {
if (dir.exists()) {
if (dir.isDirectory()) {
System.out.println(dir);
File[] files = dir.listFiles();
for (File file : files) {
getFiles(file);
}
} else {
System.out.println(dir);
readJson(dir);
}
}
}
private static void readJson(File file) throws IOException {
BufferedReader bReader = new BufferedReader(new FileReader(file));
String str = null;
StringBuffer line = new StringBuffer();
while ((str = bReader.readLine()) != null) {
line.append(str);
// line.append("\n");
}
String path = file.toString();
String value = putMsg(line.toString());
;
putMsgToText(value, path);
bReader.close();
}
private static String putMsg(String msg) {
ZHDto zhDto = new ZHDto();
String title = null;
String tags = null;
String text = null;
int i = msg.indexOf("Tags: ");
int x = msg.indexOf("]") + 1;
int y = msg.indexOf("[");
int z = msg.length();
if (i != -1 && x != -1) {
title = msg.substring(0, i).trim();
tags = msg.substring(y, x).trim();
text = msg.substring(x, z).trim();
}
zhDto.setTitle(title);
zhDto.setTags(tags);
zhDto.setText(text);
return JsonUtil.toJson(zhDto);
}
private static void putMsgToText(String message, String path) {
System.out.println(message);
File file = new File(path);// 保证创建一个文件
if (!file.getParentFile().exists()) {// 如果父目录不存在,创建父目录
file.getParentFile().mkdirs();
}
if (file.exists()) {// 如果已经存在,删除旧文件
file.delete();
}
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false)))) {
bw.write(message);
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File file = new File("C:/Users/hp/Desktop/textrt_with_tags");
FileUtils.getFiles(file);
}
}
批量读写文件并修改
最新推荐文章于 2021-02-24 14:04:20 发布