需求是这样的:老系统由apache处理,分别维护各个静态页面,现在新老系统要合并,并且要使用nginx作为服务器。此时问题出现了:apache支持相对路径,nginx不支持相对路径(认为不安全)、最终确定通过程序批量替换。
替换前:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="pragma" content="no-cache" />
<title>首页</title>
<script>var col_id=2722</script>
<!--#include virtual="/inc/css.html?encode=utf-8"-->
<!--#include virtual="../jcxx/css/s_index.htm?encode=utf-8"-->
</head>
<body>
<div id="wrap"><!-- 主体开始 -->
<div id="header"><!-- 头部开始 --> <!--#include virtual="../jcxx/head/s_index.htm"--> </div><!-- 头部结束 -->
<div id="nav"><!-- 菜单开始 --> <!--#include virtual="/dop/jcxx/nav/s_index.htm"--> </div><!-- 菜单结束 -->
<div id="main_page_home"><!--页中开始 -->
<!--#include virtual = "/dop/2013/600004/01/0017df6c91d4/sy/m_index.shtml" -->
</div><!--页中结束 -->
</div> <!-- 主体结束 -->
<div id="footer"><!-- 底部开始 -->
<!--#include virtual="/dop/jcxx/footer/s_index.htm"-->
</div><!-- 底部结束 -->
</body>
</html>
需求:要把../替换成绝对路径,当然项目上需要替换的情况非常多,不仅仅上面这种情况。
解决办法:
直接上代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UpdateRelativePath {
public static Pattern p1 = Pattern.compile("virtual(\\s)*=(\\s)*\"/"); // 以斜杠开头
public static Pattern p2 = Pattern.compile("virtual(\\s)*=(\\s)*\"\\.\\./"); // 以../开头
public static Pattern p3 = Pattern.compile("virtual(\\s)*=(\\s)*\"(?![./])"); // 以非/开头
public static Pattern p4 = Pattern.compile("href(\\s)*=(\\s)*\"(?=/)"); // href
public static Pattern p5 = Pattern.compile("src(\\s)*=(\\s)*\"(?=/)"); // src
public static Pattern p6 = Pattern.compile("url(\\s)*\\((\\s)*(?=/)"); // background:url(/images/nav_bg_red.gif)
public static Pattern p7 = Pattern.compile("/dop/2014/\\d+/\\d+/\\w+/\\w+/");//js ['公司风采','11020279010102','5997','0','/dop/2014/600015/01/5bdd9107bfc3/gsfc/','0'],
public static Pattern p8 = Pattern.compile(";file(\\s)*=(\\s)*(?=/)"); // ;file(只针对视频直播功能)
public static Pattern p9 = Pattern.compile(";skin(\\s)*=(\\s)*(?=/)"); // ;skin(只针对视频直播功能)
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
/**
* =====================sourcePath是必填参数,指定需要修改的文件夹放在哪里============================
*/
String sourcePath="/home/wwwroot/historyroadshow/";
File root = new File(sourcePath);
runAllFiles(root,sourcePath);
System.out.println("successfully,run time for :"+ (System.nanoTime()-startTime));
}
final static void runAllFiles(File dir,String sourcePath) throws Exception {
File[] fs = dir.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].isDirectory()) {
try {
runAllFiles(fs[i],sourcePath);
} catch (Exception e) {
}
}else{
if(fs[i].getAbsolutePath().indexOf(".shtml")!=-1
|| fs[i].getAbsolutePath().indexOf(".html")!=-1
|| fs[i].getAbsolutePath().indexOf(".htm")!=-1
|| fs[i].getAbsolutePath().indexOf(".css")!=-1){
replaceFile(fs[i],sourcePath);
}
else if(fs[i].getAbsolutePath().indexOf("2014")!=-1
&& fs[i].getAbsolutePath().indexOf("js")!=-1
&& fs[i].getAbsolutePath().indexOf("11mmenu.js")!=-1){
replaceJs(fs[i],sourcePath);
}
}
}
}
private static void replaceFile(File file,String sourcePath){
BufferedReader reader = null;// 创建文件读流
FileWriter writer = null;// 创建文件写流
// PrintWriter writer = null;// 创建文件写流
StringBuilder sb = new StringBuilder();// 使用StringBuilder对象保存文件内容
System.out.println("...正在处理:"+file.getAbsolutePath());
try {
//1.读出当前文件
String str="";
reader = new BufferedReader(new FileReader(file));// 使用选择的文件创建读流
while ((str=reader.readLine())!=null) {
sb.append(str);// 读入文件中的内容
sb.append("\r\n");
}
//2.获取当前文件所在目录(去掉测试目录)
String curDir = file.getParentFile().getAbsolutePath();
if(sourcePath.indexOf("//")!=-1){
sourcePath=sourcePath.replace("//", "\\");
}
if(sourcePath.indexOf("/")!=-1){
sourcePath=sourcePath.replace("/", "\\");
}
if(!"\\".equals(sourcePath.substring(sourcePath.length()-1))){
sourcePath += "\\";
}
String sourcePath2=sourcePath.replace('\\','/');
curDir = curDir.replace("\\", "/");
curDir = curDir.replace(sourcePath2, "/");
System.out.println("curDir in file:"+curDir);
String parentDir= curDir.substring(0, curDir.lastIndexOf("/"));
//3.按照不同规则进行替换
String convStr =replaceString(sb.toString(),p1,1,"");
convStr =replaceString(convStr,p2,2,parentDir);
convStr =replaceString(convStr,p3,3,curDir);
convStr =replaceString(convStr,p4,4,"");
convStr =replaceString(convStr,p5,5,"");
convStr =replaceString(convStr,p6,6,"");
convStr =replaceString(convStr,p8,8,"");
convStr =replaceString(convStr,p9,9,"");
//4.写入文件
if(flg){
writer = new FileWriter(file);
writer.write(convStr);
}
reader.close();
writer.close();
} catch (Exception e1) {
}
}
private static void replaceJs(File file,String sourcePath){
BufferedReader reader = null;// 创建文件读流
FileWriter writer = null;// 创建文件写流
// PrintWriter writer = null;// 创建文件写流
StringBuilder sb = new StringBuilder();// 使用StringBuilder对象保存文件内容
try {
//1.读出当前文件
String str="";
reader = new BufferedReader(new FileReader(file));// 使用选择的文件创建读流
while ((str=reader.readLine())!=null) {
sb.append(str);// 读入文件中的内容
sb.append("\r\n");
}
//3.按照不同规则进行替换
String convStr =replaceString(sb.toString(),p7,7,"");
//4.写入文件
if(flg){
writer = new FileWriter(file);
writer.write(convStr);
}
reader.close();
writer.close();
} catch (Exception e1) {
}
}
public static boolean flg = false;
private static String replaceString( final String str, Pattern pattern,int repalce,String dir){
StringBuilder sb2 = new StringBuilder();// 使用StringBuilder对象保存文件内容
Matcher matcher= pattern.matcher(str);
int i=0;
while(matcher.find()){
flg=true;
sb2.append(str.substring(i, matcher.start()));
String findStr = matcher.group();
if(repalce==2){
sb2.append(findStr.replace("..", ""));
}else if(repalce==7){
sb2.append("/historyroadshow"+findStr);
}
else {
sb2.append(findStr);
}
if(repalce==1){
sb2.append("historyroadshow/");
//System.out.println("p1修改后:"+sb2);
}else if(repalce==2){
sb2.append("historyroadshow" + dir+"/");
//System.out.println("p2修改后:"+sb2);
}else if(repalce==3){
sb2.append("/historyroadshow" + dir+"/");
//System.out.println("p3修改后:"+sb2);
}else if( repalce==4|| repalce==5){
sb2.append("/historyroadshow");
//System.out.println("p4、5修改后:"+sb2);
}else if(repalce==6){
sb2.append("/historyroadshow");
//System.out.println("p6修改后:"+sb2);
}else if(repalce==7){
sb2.append("index.shtml");
//System.out.println("p7修改后:"+sb2);
}else if(repalce==8){
sb2.append("/historyroadshow");
//System.out.println("p8修改后:"+sb2);
}else if(repalce==9){
sb2.append("/historyroadshow");
//System.out.println("p9修改后:"+sb2);
}
i = matcher.end();
}
sb2.append(str.substring(i));
pattern=null;
return sb2.toString();
}
}
替换后效果:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="pragma" content="no-cache" />
<title>首页</title>
<script>var col_id=2722</script>
<!--#include virtual="/historyroadshow/inc/css.html?encode=utf-8"-->
<!--#include virtual="/historyroadshow/dop/2013/600004/01/0017df6c91d4/jcxx/css/s_index.htm?encode=utf-8"-->
</head>
<body>
<div id="wrap"><!-- 主体开始 -->
<div id="header"><!-- 头部开始 --> <!--#include virtual="/historyroadshow/dop/2013/600004/01/0017df6c91d4/jcxx/head/s_index.htm"--> </div><!-- 头部结束 -->
<div id="nav"><!-- 菜单开始 --> <!--#include virtual="/historyroadshow/dop/jcxx/nav/s_index.htm"--> </div><!-- 菜单结束 -->
<div id="main_page_home"><!--页中开始 -->
<!--#include virtual = "/historyroadshow/dop/2013/600004/01/0017df6c91d4/sy/m_index.shtml" -->
</div><!--页中结束 -->
</div> <!-- 主体结束 -->
<div id="footer"><!-- 底部开始 -->
<!--#include virtual="/historyroadshow/dop/jcxx/footer/s_index.htm"-->
</div><!-- 底部结束 -->
</body>
</html>