开发者社区> 问答> 正文

java 根据log文件中是否关键信息,来删除文档 报错

"

在E:/desktop/1文件夹下有很多文件,见下
<span class=""img-wrap""><img referrerpolicy=""no-referrer"" data-src=""/img/bVoLto"" src=""https://cdn.segmentfault.com/v-5e8d8dec/global/img/squares.svg"" alt=""clipboard.png"" title=""clipboard.png"" />
需要对这些log文件进行处理,其中有些log文件中包含了很多无用信息,对于这些包含多无用信息的log文件处理是将这些文件删除掉。文件中的内容见下,比如

下面是我写的程序,但不能删除文件,求大神指点下!
谢谢。。。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class ProcessMain {

    static String str = "";
    
    public static void main(String[] args) throws Exception{
        String path = "E:/desktop/1";        
        getDirList(path);
    }
    
    public static void read(String filepath)throws Exception{
        
        //read folder and iterate every subfile
        File f = new File(filepath);
        FileReader reader = new FileReader(f);
        BufferedReader br = new BufferedReader(reader);
        while((str = br.readLine()) != null){
            if(str.contains("NoID")){
                f.delete();
            }

        }
        br.close();
    }
    
    public static void getDirList(String path) throws Exception {
        File f = new File(path);
        if(f != null){
            if(f.isDirectory()){
              File[] fs = f.listFiles();
              for (File file : fs) {
                  if (file.isFile()) {
                      if(file.length() > 0)
                          read(file.toString());
                  } 
                  else
                      getDirList(file.getPath());
              }    
            }
        }
    }
}
" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/e6d5ba683a80451eac7112b2c4dc33bc.png)

展开
收起
因为相信,所以看见。 2020-05-26 13:56:00 742 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    "

    主要改了下 read 方法,写了注释,其它地方你自己看着改呵。
    这里 read 改名叫 checkToDelete 比较合适

    <code class=""java"">    public static void read(File f) throws Exception { //read folder and iterate every subfile // 直接传参数就传 File 对象,不需要重新生成了 // File f = new File(filepath); FileReader reader = new FileReader(f); BufferedReader br = new BufferedReader(reader);

        boolean shouldDelete = false;
        String str;
        while ((str = br.readLine()) != null) {
            if (str.contains("NoID")) {
                // 这里你的文件还是打开的,所以不能删除
                // 在这里应该做个标记,关闭之后再来删除
                // f.delete();
                shouldDelete = true;
                break;
            }
    
        }
        br.close();
    
        // 如果标记删除了,在 `close()` 之后就可以删了
        if (shouldDelete) {
            f.delete();
        }
    }</code></pre>"
    

    image.png

    2020-05-27 10:17:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载