批量替換頁面中的路徑 相對路徑轉換爲絕對路徑

需求是這樣的:老系統由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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章