"
在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());
              }    
            }
        }
    }
}
" 
                    版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
"
主要改了下 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>"
