packagecom.lmt.service.file;importjava.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.InputStreamReader;importjava.io.Reader;importorg.springframework.stereotype.Component;importcom.lmt.config.UrlConstants;
@Componentpublic classParseFile {/*** 解析html文件
*@paramfile
*@return
*/
publicString readHtml(File file){
String body= "";try{
FileInputStream iStream= newFileInputStream(file);
Reader reader= newInputStreamReader(iStream);
BufferedReader htmlReader= newBufferedReader(reader);
String line;boolean found = false;while (!found && (line = htmlReader.readLine()) != null) {if (line.toLowerCase().indexOf("
的前面可能存在空格found = true;
}
}
found= false;while (!found && (line = htmlReader.readLine()) != null) {if (line.toLowerCase().indexOf("
found= true;
}else{//如果存在圖片,則將相對路徑轉換為絕對路徑
String lowerCaseLine =line.toLowerCase();if (lowerCaseLine.contains("src")) {//這里是定義圖片的訪問路徑
String directory = "D:/test";//如果路徑名不以反斜杠結尾,則手動添加反斜杠
/*if (!directory.endsWith("\\")) {
directory = directory + "\\";
}*/
//line = line.substring(0, lowerCaseLine.indexOf("src") + 5) + directory + line.substring(lowerCaseLine.indexOf("src") + 5);
/*String filename = extractFilename(line);
line = line.substring(0, lowerCaseLine.indexOf("src") + 5) + directory + filename + line.substring(line.indexOf(filename) + filename.length());*/
//如果該行存在多個元素,則分行進行替代
String[] splitLines = line.split("
for (int i = 0; i < splitLines.length; i++) {if (splitLines[i].toLowerCase().startsWith("src")) {
splitLines[i]= splitLines[i].substring(0, splitLines[i].toLowerCase().indexOf("src") + 5)+directory+ splitLines[i].substring(splitLines[i].toLowerCase().indexOf("src") + 5);
}
}//最后進行拼接
line = "";for (int i = 0; i < splitLines.length - 1; i++) { //循環次數要-1,因為最后一個字符串后不需要添加
line = line + splitLines[i] + "
}
line= line + splitLines[splitLines.length - 1];
}
body= body + line + "\n";
}
}
htmlReader.close();//System.out.println(body);
}catch(Exception e) {
e.printStackTrace();
}returnbody;
}/***
*@paramhtmlLine 一行html片段,包含元素
*@return文件名*/
public staticString extractFilename(String htmlLine) {int srcIndex = htmlLine.toLowerCase().indexOf("src=");if (srcIndex == -1) { //圖片不存在,返回空字符串
return "";
}else{
String htmlSrc= htmlLine.substring(srcIndex + 4);char splitChar = '\"'; //默認為雙引號,但也有可能為單引號
if (htmlSrc.charAt(0) == '\'') {
splitChar= '\'';
}
String[] firstSplit=htmlSrc.split(String.valueOf(splitChar));
String path= firstSplit[1]; //第0位為空字符串
String[] secondSplit = path.split("[/\\\\]"); //匹配正斜杠或反斜杠
return secondSplit[secondSplit.length - 1];
}
}
}