先把所要添加监测内容的html页面存放到指定目录.
package struts2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class HandleFiles {
public static int count=0;//493
public static void getfiles(String path){
File file=new File(path);
try {
count++;
String returnStr = "";
InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");
BufferedReader reader=new BufferedReader(read);
String line;
while ((line = reader.readLine()) !=null) {
returnStr+=line+"\n";
}
//returnStr = new String(returnStr.getBytes("GBK"), "UTF-8");
returnStr=returnStr.replace("</head>",getContent());
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
BufferedWriter writer=new BufferedWriter(write);
writer.write(returnStr);
writer.close();
reader.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getContent(){
String str="";
str+= "<script>\n" +
" (function(a, e, f, g, b, c, d) {a.ClickiTrackerName = b;\n" +
" a[b] = a[b] || function() {(a[b].queue = a[b].queue || []).push(arguments)};\n" +
" a[b].start = +new Date; c = e.createElement(f); d = e.getElementsByTagName(f)[0];\n" +
" c.async = 1; c.src = g; d.parentNode.insertBefore(c, d)\n" +
" })(window, document, 'script', ('https:' == document.location.protocol ? 'https://stm-collect' : 'http://stm-cdn') + '.cn.miaozhen.com/clicki.min.js', 'stm_clicki');\n" +
" stm_clicki('create', 'dc-1286', 'auto');\n" +
" stm_clicki('send', 'pageview');\n" +
"</script>\n";
str+="</head>";
return str;
}
/**
* 读取某个文件夹下的所有文件
*/
public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
try {
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("文件");
System.out.println("path=" + file.getPath());
getfiles(file.getPath());
} else if (file.isDirectory()) {
System.out.println("文件夹");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("path=" + readfile.getPath());
getfiles(readfile.getPath());
} else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return true;
}
public static void main(String[] args) {
String path="D://bak";
try {
readfile(path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("total:"+count);
}
}