import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceDate {
public static void main(String[] args) {
String reg = "(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)[0-9]{2})";
Pattern pattern = Pattern.compile (reg);
// 读取文本文件
try {
File dir = new File("G:/ssmdb-data/");
File file[] = dir.listFiles();
for (int i = 0; i < file.length; i++) {
String filePath = file[i].getAbsolutePath();
String fileName = file[i].getName();
String encoding = "UTF-8"; // 字符编码(可解决中文乱码问题 )
File fileTemp = new File(filePath);
if (fileTemp.isFile() && fileTemp.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(fileTemp), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTXT = null;
String destContent = "";
while ((lineTXT = bufferedReader.readLine()) != null) {
String content = lineTXT.toString().trim();
content = content.replaceAll("TO_DATE\\(", "");
content = content.replaceAll(", 'MM/DD/YYYY HH24:MI:SS'\\)", "");
destContent += content;
System.out.println(content);
}
read.close();
Matcher matcher = pattern.matcher (destContent);
while (matcher.find ())
{
System.out.println (matcher.group ());
String oldDate = matcher.group ();
String[] oldDateArr = oldDate.split("/");
String newDate = oldDateArr[2]+"-" + oldDateArr[0] +"-" + oldDateArr[1];
destContent = destContent.replaceAll(oldDate, newDate);
}
//将转换的文本写入原来的文件中
PrintStream ps = new PrintStream(new FileOutputStream(fileTemp));
ps.println(destContent);// 往文件里写入字符串
ps.flush();
ps.close();
System.out.println(fileName + " is writen!");
} else {
System.out.println("找不到指定的文件!");
}
}
} catch (Exception e) {
System.out.println("读取文件内容操作出错");
e.printStackTrace();
}
}
}
将文件中TO_DATE('04/05/2016 13:16:14', 'MM/DD/YYYY HH24:MI:SS')替换成'2016-04-05 13:16:14'
最新推荐文章于 2023-11-07 10:43:44 发布
本文介绍了一个使用Java编写的工具,该工具能够批量读取指定目录下的文本文件,并将文件内的日期格式从MM/DD/YYYY转换为YYYY-MM-DD格式。此外,还移除了与日期相关的特定字符串。
1949

被折叠的 条评论
为什么被折叠?



