代码改变世界

多线程下bufferedwriter若不关闭并不能记下所有log

2021-05-30 21:48  钱先生  阅读(191)  评论(0编辑  收藏  举报

问题

一个很简单的多线程修改文件夹中特定文件名的程序。用bufferedwriter把待修改的文件名(包括完整地址)都记在Log里,以做检查之用。

发现如果不在最后关闭bw的话,每个文件夹只能写上最后一个文件的名字。即使bw.flush()也没有什么帮助。\

 

package SamplePackage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class WebdriverDemo {

    public static void main(String[] args) {
        String path = "C:\\Users\\XXX\\Desktop\\temp";
        String logPath = "C:\\Users\\XXX\\Desktop\\temp\\log.txt";
        reviseName(path,logPath);

    }
    
    public static void reviseName(String path, String logPath) {
        File dir = new File(path);
        File log = new File(logPath);
        
        BufferedWriter bw=null;
        try {
            bw = new BufferedWriter(new FileWriter(log,true));
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        if(dir.exists()) {
            File[] subFile = dir.listFiles();
            for(File file:subFile) {
                if(file.isDirectory()) {
                    String subpath = file.getAbsolutePath();
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            reviseName(subpath,logPath);
                            
                        }
                        
                    }).start();
                } else{
                    String name = file.getName();
                    String parentPath = file.getAbsolutePath();
                    if(name.startsWith("Abc")){
                        try {
                            
                            bw.flush();
                            bw.write(parentPath);
                            bw.newLine();
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                        file.renameTo(new File(parentPath.replace("Abc","AAA")));
                        
                    }
                    
                }
            }
            
            try {
                if(bw!=null) {
                    bw.close();
                }
                
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        
    }

}
View Code