java 查找文件包含某个字符并删除这一行

该Java程序用于批处理指定文件夹下的.java文件,查找并移除包含特定字符(@AutoLog)的行,将处理后的文件复制到新目录。它使用FileFilter筛选.java文件,通过BufferedReader和PrintWriter读写文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如题:

我们常常需要在批处理一些文件,比如某个文件夹下的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();
            }
        }
    }


}

Java删除文本文件中的某个特定字符串通常涉及到读取整个文件内容,替换需要移除的字符串,然后将修改后的内容写回原文件。以下是一个简单的步骤描述: 1. **打开文件**:首先,你需要使用`FileInputStream`和`BufferedReader`打开文件读取其内容。 ```java File file = new File("your_file.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; StringBuilder contentBuilder = new StringBuilder(); ``` 2. **逐行读取处理**:遍历文件中的一行,检查是否包含你要删除字符串,如果包含就跳过,如果不包含则添加到`StringBuilder`中。 ```java while ((line = reader.readLine()) != null) { if (!line.contains("string_to_remove")) { contentBuilder.append(line); contentBuilder.append("\n"); } } ``` 3. **关闭流写回文件**:读取完成后,关闭当前的流使用`FileWriter`和`BufferedWriter`创建一个新的流,将处理过的字符串写回到新的文件中。 ```java reader.close(); writer = new BufferedWriter(new FileWriter(file)); // 假设file变量保存了要写入的新路径 writer.write(contentBuilder.toString()); writer.close(); ``` 4. **异常处理**:在实际操作中,记得加上适当的异常处理,例如`FileNotFoundException`, `IOException`等。 这个过程假设你已经有了替换字符串的目标位置,如果是动态查找和替换,可能会更复杂一些。另外,如果你只是简单地想删除一行,可以考虑直接操作文件内容而无需全部读取。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值