如题:
我们常常需要在批处理一些文件,比如某个文件夹下的java文件包含某个字符或者某种条件,将这些字符清理掉,
如果比较多的话 处理起来比较麻烦,可以写程序进行批处理!
package com.zwsafety.portal;
import java.io.*;
/**
* @author Lenovo
*/
public class TestReadFile {
public static void main(String[] args) throws IOException {
String path = "F:\\idea\\V1.3\\sdmine-main\\src\\main\\java\\com\\zwsafety\\portal\\activiti\\controller";
String prefix = ".java";
String containsStr = "@AutoLog";
deleteStrAndCopy(path,prefix,containsStr);
}
/**
* 在某哥文件夹下 查找所有的文件后缀 如果匹配到字符 将文件复制到 指定文件 下
* @param path 需要查找文件夹的路径
* @param prefix 需要查找的文件类型
* @param containsStr 包含的字符
* @throws IOException
*/
public static void deleteStrAndCopy(String path,String prefix,String containsStr) throws IOException {
String destPath = path+"\\bb\\";
isExistDir(destPath);
FileFilter fileFilter = new FileFilter() {
public boolean accept(File pathname) {
if(pathname.getName().toLowerCase().endsWith(prefix)){
return true;
}
return false;
}
};
File file = new File(path);
File[] files = file.listFiles(fileFilter);
for (File htmlFile:files){
PrintWriter printWriter=new PrintWriter(destPath+htmlFile.getName());
BufferedReader bufferedReader = new BufferedReader(new FileReader(htmlFile));
String line = bufferedReader.readLine();
while (line != null){
if(!(line.contains(containsStr))){
printWriter.println(line);
printWriter.flush();
}
line = bufferedReader.readLine();
}
System.out.println("写完 "+htmlFile.getPath());
bufferedReader.close();
printWriter.flush();
printWriter.close();
}
}
/**
* 判断多级路径是否存在,不存在就创建
* @param filePath 支持带文件名的Path:如:D:\news\2014\12\abc.text,和不带文件名的Path:如:D:\news\2014\12
*/
public static void isExistDir(String filePath) {
String paths[] = {""};
//切割路径
try {
//File对象转换为标准路径并进行切割,有两种windows和linux
String tempPath = new File(filePath).getCanonicalPath();
//windows
paths = tempPath.split("\\\\");
//linux
if(paths.length==1){paths = tempPath.split("/");}
} catch (IOException e) {
System.out.println("切割路径错误");
e.printStackTrace();
}
//判断是否有后缀
boolean hasType = false;
if(paths.length>0){
String tempPath = paths[paths.length-1];
if(tempPath.length()>0){
if(tempPath.indexOf(".")>0){
hasType=true;
}
}
}
//创建文件夹
String dir = paths[0];
// 注意此处循环的长度,有后缀的就是文件路径,没有则文件夹路径
for (int i = 0; i < paths.length - (hasType?2:1); i++) {
try {
//采用linux下的标准写法进行拼接,由于windows可以识别这样的路径,所以这里采用警容的写法
dir = dir + "/" + paths[i + 1];
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdir();
System.out.println("成功创建目录:" + dirFile.getCanonicalFile());
}
} catch (Exception e) {
System.err.println("文件夹创建发生异常");
e.printStackTrace();
}
}
}
}