由於一些不可說的原因,單位網站需要備份一個鏡像到本地,以備不時之需。此爲背景。
由於源代碼是靜態網頁,先考慮手工備份,手工下載頁面和相關資源,後來工作量太大,放棄。
網上查工具,先試了teleport pro,按照網上教程,不知道爲何各種無法下載。
再查工具,webzip,下載了,綠色破解版,按照教程配置了,下載,順利,個別頁面和資源失敗,影響不大。反正手工需要調整。
本地nginx代理資源,逐個查看404,下載css,js,img,html。修改頁面超鏈接(很多超鏈接是非html後綴的,與目錄不匹配)。
其中最坑的地方是,所有頁面都有一個公共的頁面頭部(包含菜單),內容非常多。這就說明所有的頁面頭部都需要修改css,js,超鏈接的內容。這個工作量。。。作爲程序員,只能自己動手了。
1、先準備一個正確的本地可訪問的頭部html內容,存入一個文本文件。
2、程序訪問所有html,定位需要替換的部分,將預先準備好的內容替換。
廢話不多,上java代碼:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Rewrite {
public static void main(String[] args) {
String path = "C:\\soft\\nginx-1.17.10\\html";
String suffix=".html";
String source = "C:\\Users\\lenovo\\Desktop\\s.txt";
String begin="<!DOCTYPE html>";
String end="<div class=\"main\">";
try {
String s = readSource(source);
System.out.println("rp len:"+s.length());
rewrite(path,s,suffix,begin,end);
}catch (Exception e) {
e.printStackTrace();
}
}
private static String readSource(String source) throws Exception {
return new String(Files.readAllBytes(Paths.get(source)));
}
private static void rewrite(final String path,final String s,final String suffix,final String begin,final String end) throws Exception {
if(Files.isDirectory(Paths.get(path))) {
System.out.println("folder path:" +path);
for(File t : new File(path).listFiles()) {
rewrite(t.getAbsolutePath(),s,suffix,begin,end);
}
}else {
System.out.println("file path:" +path);
if(path.endsWith(suffix)) {
String t = new String(Files.readAllBytes(Paths.get(path)));
System.out.println("ori len:"+t.length());
int beginindex = t.indexOf(begin);
if(-1 == beginindex) {
System.out.println("begin tag unfound");
return;
}
String pre = t.substring(0,beginindex);
System.out.println("pre len:"+pre.length());
int endindex = t.indexOf(end);
if(-1 == endindex) {
System.out.println("end tag unfound");
return;
}
String sf = t.substring(endindex);
System.out.println("sf len:"+sf.length());
String n = pre + s +sf;
System.out.println("new len:"+n.length());
if(t.length() == n.length()) {
System.out.println("file has dealed");
return;
}
Files.write(Paths.get(path), n.getBytes(), StandardOpenOption.WRITE,StandardOpenOption.TRUNCATE_EXISTING);
}
}
}
}
這裏需要補充的是定位方法是使用html標籤指定開始和結束標籤,然後將這一部分替換掉。比如我需要替換從開頭到div class="main"的部分。