首页 > 编程语言 > 详细

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

时间:2021-05-31 00:15:19      阅读:27      评论:0      收藏: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

 

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

原文:https://www.cnblogs.com/cheese320/p/14829271.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!