zoukankan      html  css  js  c++  java
  • 多线程下bufferedwriter若不关闭并不能记下所有log

    问题

    一个很简单的多线程修改文件夹中特定文件名的程序。用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
  • 相关阅读:
    003.同时Ping多个IP(select实现IO复用,信号计时),ping程序升级版
    002.ICMP--拼接ICMP包,实现简单Ping程序(原始套接字)
    001.linux下clock()检测程序运行时间
    django form的函数用法
    命令注入利用语句
    小白审计JACKSON反序列化漏洞
    代码审计小工具
    Burp插件开发--应用篇
    burp插件开发--基础篇
    JAVA web网站代码审计--入门
  • 原文地址:https://www.cnblogs.com/cheese320/p/14829271.html
Copyright © 2011-2022 走看看