目录
概述
需求是:有很多需要修改的文件,利用正则表达式匹配修改这些文本,并保存。
文末有完整的代码下载地址和完整代码贴出来。
实现的功能
- 实现赛选出指定文件夹中的xml文件(也可以更改为其他的)
- 实现了将xml中的内容取出存在stringbuffer中,在对其进行修改
- 用正则表达式匹配指定的内容,然后修改替换指定的内容,并写入文件
效果图
可以看见,所有xml文件都被修改了。
修改前
修改后
代码
需要导入的包
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
查找指定后缀文件
首先写了一个内部类,用来过滤指定文件夹中的指定后缀的文件。
//匹配.xml后缀文件内部类
public class FileFilter implements FilenameFilter
{
private String filterRule;
public FileFilter(String filter)
{
this.filterRule = filter;
}
@Override
public boolean accept(File dir, String name) {
if(name.lastIndexOf('.')>0)
{
// get last index for '.' char
int lastIndex = name.lastIndexOf('.');
// get extension
String str = name.substring(lastIndex);
// match path name extension
if(str.equals(this.filterRule))
{
return true;
}
}
return false;
}
}
调用方式
FilenameFilter fileNameFilter = fileFilter .new FileFilter(".xml") ;
指定文件匹配替换内容
replace主要是接收:
1.需要修改的文件路径
2.正则表达式的匹配规则
3.需要写入的内容
/*
替换文件内容
传递的参数1.path文件路径,
2.patString:正则表达式(需要匹配的内容)
3.需要替换的内容
*/
public static void replace(File path,String patString2,String replacement2) {
// 正则表达式
String patt = patString2;
// 测试的输入字符串
String str="";
File file=path;
try {
FileInputStream in=new FileInputStream(file);
// size 为字串的长度 ,这里一次性读完
int size=in.available();
byte[] buffer=new byte[size];
in.read(buffer);
in.close();
str=new String(buffer,"UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("读取到文件的信息为-----------------------------------:" + str);
// 从正则表达式实例中运行方法并查看其如何运行
Pattern r = Pattern.compile(patt,Pattern.CASE_INSENSITIVE);
Matcher m = r.matcher(str);
//System.out.println("替换成的文件为----------------------------------------------------:" + m.replaceAll("favour"));
// appendReplacement方法
m.reset();
StringBuffer sb = new StringBuffer();
while (m.find()) {
// 将匹配之前的字符串复制到sb
m.appendReplacement(sb, replacement2);
}
//sb中储存的只是匹配结束位置的信息,appendTail是加上最后未匹配到的部分文本内容,从而使内容完整
m.appendTail(sb);
//System.out.println("str是------------------------"+str);
//System.out.println("sb是------------------------"+sb);
//控制台测试
/*System.out.println(sb.toString());
m.appendTail(sb);
System.out.println(sb.toString());*/
try{
FileWriter fileWriter = new FileWriter(path);
fileWriter.write(sb.toString());
//System.out.println(sb);
fileWriter.close();
}catch (Exception e){
e.printStackTrace();
}
}
主函数
主函数调用查找xml方法和替换文本内容
public static void main(String[] args)
{
File f = null;
File[] paths;
//需要替换的内容
String replacement = "from {$publicdb}.";
AddPrefixXml fileFilter = new AddPrefixXml();
try{
f = new File("D:\\E10\\base-common-web\\base-common-web-service\\src\\main\\java\\com\\weaver\\base\\common\\web\\dao");
// 文件文件名字过滤器
FilenameFilter fileNameFilter = fileFilter .new FileFilter(".xml") ;
paths = f.listFiles(fileNameFilter);
for(File path:paths){
/*
传递的参数
1.path文件路径,
2.patString:正则表达式(需要匹配的内容)
3.需要替换的内容
*/
replace(path,"from [a-z]",java.util.regex.Matcher.quoteReplacement("from {$publicdb}."));
replace(path,"insert into [a-z]",java.util.regex.Matcher.quoteReplacement("insert into {$publicdb}."));
replace(path," update [a-z]",java.util.regex.Matcher.quoteReplacement("update {$publicdb}."));
replace(path,"left join [a-z]",java.util.regex.Matcher.quoteReplacement("LEFT JOIN {$publicdb}."));
}
}catch(Exception e)
{
e.printStackTrace();
}
}
最后完整代码
本次是对所有xml文件的中,所有表名的前面加上一个前缀,如果需要修改其他内容当然只需要填入需要匹配的正则表达式,和需要写入的内容即可。
package com.weaver.base.common.web.util;
/**
* @Date:Created in 17:48 2022/2/14
* 用于表名前加前缀
*/
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AddPrefixXml {
//匹配.xml后缀文件内部类
public class FileFilter implements FilenameFilter
{
private String filterRule;
public FileFilter(String filter)
{
this.filterRule = filter;
}
@Override
public boolean accept(File dir, String name) {
if(name.lastIndexOf('.')>0)
{
// get last index for '.' char
int lastIndex = name.lastIndexOf('.');
// get extension
String str = name.substring(lastIndex);
// match path name extension
if(str.equals(this.filterRule))
{
return true;
}
}
return false;
}
}
/*
替换文件内容
传递的参数1.path文件路径,
2.patString:正则表达式(需要匹配的内容)
3.需要替换的内容
*/
public static void replace(File path,String patString2,String replacement2) {
// 正则表达式
String patt = patString2;
// 测试的输入字符串
String str="";
File file=path;
try {
FileInputStream in=new FileInputStream(file);
// size 为字串的长度 ,这里一次性读完
int size=in.available();
byte[] buffer=new byte[size];
in.read(buffer);
in.close();
str=new String(buffer,"UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("读取到文件的信息为-----------------------------------:" + str);
// 从正则表达式实例中运行方法并查看其如何运行
Pattern r = Pattern.compile(patt,Pattern.CASE_INSENSITIVE);
Matcher m = r.matcher(str);
//System.out.println("替换成的文件为----------------------------------------------------:" + m.replaceAll("favour"));
// appendReplacement方法
m.reset();
StringBuffer sb = new StringBuffer();
while (m.find()) {
// 将匹配之前的字符串复制到sb
m.appendReplacement(sb, replacement2);
}
//sb中储存的只是匹配结束位置的信息,appendTail是加上最后未匹配到的部分文本内容,从而使内容完整
m.appendTail(sb);
//System.out.println("str是------------------------"+str);
//System.out.println("sb是------------------------"+sb);
//控制台测试
/*System.out.println(sb.toString());
m.appendTail(sb);
System.out.println(sb.toString());*/
try{
FileWriter fileWriter = new FileWriter(path);
fileWriter.write(sb.toString());
//System.out.println(sb);
fileWriter.close();
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args)
{
File f = null;
File[] paths;
//需要替换的内容
//String replacement = "from {$publicdb}.";
AddPrefixXml fileFilter = new AddPrefixXml();
try{
f = new File("D:\\E10\\base-common-web\\base-common-web-service\\src\\main\\java\\com\\weaver\\base\\common\\web\\dao");
// 文件文件名字过滤器
FilenameFilter fileNameFilter = fileFilter .new FileFilter(".xml") ;
paths = f.listFiles(fileNameFilter);
for(File path:paths){
/*
传递的参数
1.path文件路径,
2.patString:正则表达式(需要匹配的内容)
3.需要替换的内容 LEFT OUTER JOIN
*/
replace(path,"\\sfrom\\s*",java.util.regex.Matcher.quoteReplacement(" from {$publicdb}."));
replace(path,"insert into\\s*",java.util.regex.Matcher.quoteReplacement("insert into {$publicdb}."));
replace(path,"[^<\"/]update ",java.util.regex.Matcher.quoteReplacement(" update {$publicdb}."));
replace(path,"left join\\s*",java.util.regex.Matcher.quoteReplacement("LEFT JOIN {$publicdb}."));
replace(path,"RIGHT JOIN\\s*",java.util.regex.Matcher.quoteReplacement("RIGHT JOIN {$publicdb}."));
replace(path,"INNER JOIN\\s*",java.util.regex.Matcher.quoteReplacement("INNER JOIN {$publicdb}."));
replace(path,"LEFT OUTER JOIN\\s*",java.util.regex.Matcher.quoteReplacement("LEFT OUTER JOIN {$publicdb}."));
//去掉子查询前面的{$publicdb}.
replace(path,"from \\{\\$publicdb\\}\\.\\(",java.util.regex.Matcher.quoteReplacement("from ("));
replace(path,"from \\{\\$publicdb\\}\\.\\s",java.util.regex.Matcher.quoteReplacement("from "));
replace(path,"LEFT JOIN \\{\\$publicdb\\}\\.\\s",java.util.regex.Matcher.quoteReplacement("LEFT JOIN "));
replace(path,"LEFT JOIN \\{\\$publicdb\\}\\.\\(",java.util.regex.Matcher.quoteReplacement("LEFT JOIN ("));
replace(path,"LEFT JOIN \\{\\$publicdb\\}\\.\\<",java.util.regex.Matcher.quoteReplacement("LEFT JOIN <"));
replace(path,"RIGHT JOIN \\{\\$publicdb\\}\\.\\s",java.util.regex.Matcher.quoteReplacement("RIGHT JOIN "));
replace(path,"RIGHT JOIN \\{\\$publicdb\\}\\.\\(",java.util.regex.Matcher.quoteReplacement("RIGHT JOIN ("));
replace(path,"INNER JOIN \\{\\$publicdb\\}\\.\\s",java.util.regex.Matcher.quoteReplacement("INNER JOIN "));
replace(path,"INNER JOIN \\{\\$publicdb\\}\\.\\(",java.util.regex.Matcher.quoteReplacement("INNER JOIN ("));
replace(path,"LEFT OUTER JOIN \\{\\$publicdb\\}\\.\\s",java.util.regex.Matcher.quoteReplacement("LEFT OUTER JOIN "));
//保证{$publicdb}.后面没有空格和<choose>
replace(path,"\\{\\$publicdb\\}\\.\\s*",java.util.regex.Matcher.quoteReplacement("{$publicdb}."));
replace(path,"\\{\\$publicdb\\}\\.\\<",java.util.regex.Matcher.quoteReplacement("<"));
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
例子的xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ConfigExtDao">
<insert id="insert" parameterType="com.ConfigExt">
insert into {$publicdb}.ONFIG_EXT (ID, CONFIG_KEY, CONFIG_VALUE,MODULE,USER_ID,UPDATE_TIME,TENANT_KEY)
VALUES (#{id},#{configKey},#{configValue},#{module},#{userId},#{updateTime},#{tenantKey})
</insert>
<insert id="saveConfigExts">
<if test="configExts!=null and configExts.size()>0">
insert into {$publicdb}.ONFIG_EXT (ID, CONFIG_KEY, CONFIG_VALUE,MODULE,USER_ID,UPDATE_TIME,TENANT_KEY)
VALUES
<foreach item="configExt" index="index" collection="configExts" open="" separator="," close="">
(#{configExt.id},#{configExt.configKey},#{configExt.configValue},#{configExt.module},#{configExt.userId},#{configExt.updateTime},#{configExt.tenantKey})
</foreach>;
</if>
</insert>
<update id="update" parameterType="com.ConfigExt">
UPDATE CONFIG_EXT SET
USER_ID = #{userId},
CONFIG_VALUE = #{configValue},
UPDATE_TIME = #{updateTime}
WHERE ID = #{id}
</update>
<update id="updateConfigExts">
<foreach collection="configExts" item="configExt" separator=";" close="" open="">
update {$publicdb}.ONFIG_EXT
<set>
<if test="configExt.userId!=null">
USER_ID = #{configExt.userId},
</if>
<if test="configExt.configValue!=null">
CONFIG_VALUE = #{configExt.configValue},
</if>
<if test="configExt.updateTime!=null">
UPDATE_TIME = #{configExt.updateTime}
</if>
</set>
WHERE ID = #{configExt.id}
</foreach>
</update>
<update id="resetConfigExt">
UPDATE CONFIG_EXT SET CONFIG_VALUE = '0' WHERE CONFIG_KEY = #{configKey} AND TENANT_KEY = #{tenantKey}
</update>
<delete id="deleteConfigExts">
DELETE from {$publicdb}.ONFIG_EXT WHERE CONFIG_KEY = #{configKey} AND TENANT_KEY = #{tenantKey}
</delete>
<select id="getById" resultType="com.ConfigExt">
SELECT * from {$publicdb}.ONFIG_EXT WHERE ID = #{id}
</select>
<select id="queryConfigExtByModule" resultType="com.ConfigExt">
SELECT * from {$publicdb}.ONFIG_EXT
WHERE CONFIG_KEY = #{configKey} AND MODULE = #{module} AND TENANT_KEY = #{tenantKey}
</select>
<select id="queryTenantConfigExt" resultType="com.weaver.ConfigExt">
SELECT * from {$publicdb}.ONFIG_EXT
WHERE TENANT_KEY = #{tenantKey} AND CONFIG_KEY = #{configKey} AND MODULE IS NULL
</select>
<select id="queryConfigExts" resultType="com.weaver.ConfigExt">
SELECT * from {$publicdb}.ONFIG_EXT
WHERE CONFIG_KEY = #{configKey} AND TENANT_KEY = #{tenantKey}
</select>
</mapper>