Java monitors folders in real time, realizes real-time monitoring of files received by WeChat, and removes the read-only attribute of files

foreword

As we all know, Xiaomei Software does not do any personnel work every time it is updated. I forgot which version was updated last time, and all received files are read-only files. Although you only need to right-click the property and uncheck the read-only option, it is a bit troublesome to do this every time you receive a file. So I wrote a small tool myself and let the tool do this for us.

We use WatchService to monitor folder changes in real time, and because it is asynchronous, there is no performance burden, so there is no need to worry about performance.

accomplish

First of all, we need to create a WeChat folder path.txt file in the root directory of the project, and set up our own WeChat file directory here (because everyone’s directory is different, I need to package it into an exe program later, so this directory cannot Write to death.)

Once set up, we can start writing code.

the code

import java.io.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 监听并清除文件的只读属性
 */
public class RemoveReadOnly {
    
    

    /** 微信文件夹路径 */
    private static String folderPath = "";

    /**
     * 获取当前年月(yyyy-MM)
     * 因为微信文件目录是按年月创建的,所以设置目录时只需要设置到 FileStorage ——》》File 文件夹即可。
     * 每个月接收的文件,我们只监听当前月所在的文件夹。
     */
    private static String currenMonth(){
    
    
        SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM");
        return sfd.format(new Date());
    }

    /**
     * 读取设置的路径
     */
    private static void readPath() throws IOException {
    
    
        String path = System.getProperty("user.dir");//打包用的路径:jar包或exe程序所在目录名
        InputStreamReader fReader = new InputStreamReader(new FileInputStream(path+"/微信文件夹路径.txt"),"UTF-8");
        BufferedReader reader = new BufferedReader(fReader);
        String lineTxt=null;
        while((lineTxt=reader.readLine())!=null){
    
    
            if (lineTxt.length()>0){
    
    
                folderPath = lineTxt + currenMonth();
                break;
            }
        }
    }

    /**
     * 监听文件夹,并去掉文件的只读属性
     */
    public static void removeReadOnly() throws IOException{
    
    
        File f = new File(folderPath);
        if (!f.exists()) {
    
    
            Log.msg("路径不存在,请检查 微信文件夹路径.txt 文件是否设置了路径,或设置的路径是否正确!");
        }
        // 获取文件系统的WatchService对象
        WatchService watchService = FileSystems.getDefault().newWatchService();
        // 注册监听事件
        Path dir = Paths.get(folderPath);
        dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
        while (true) {
    
     // 循环监听
            WatchKey key = null;
            try {
    
    
                key = watchService.take();
            } catch (InterruptedException e) {
    
    
                return;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
    
    
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) continue;
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filename = ev.context();
                File file = dir.resolve(filename).toFile();
                if (file.exists() && !file.canWrite()) {
    
     // 判断文件是否可以写入
                    file.setWritable(true); // 将文件的只读属性去掉
                    Log.msg("将文件 "+filename.toString()+" 的只读属性去掉了!");
                }
            }
            boolean valid = key.reset();
            if (!valid) {
    
    
                break;
            }
        }
    }

    public static void main(String[] args) {
    
    
        try {
    
    
            readPath();
            removeReadOnly();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
}

Output log (because the software exe4j used in packaging into exe, there is an item setting that can automatically output our log to a file, here we don’t need to use FileHandler to set the output to file separately)

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;

public class Log {
    
    
    private static final Logger logger = Logger.getLogger("MyLogger");
    private static final SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 格式化时间,用于输出日志
     */
    private static String currentTime(){
    
    
        return sfd.format(new Date());
    }

    /**
     * 设置消息
     */
    public static void msg(String msg){
    
    
        logger.info(currentTime()+" "+msg);
    }
}

The above is all the code, isn't it very simple!

The final structure is like this.
insert image description here
It can be used after testing, and it can be monitored even if there is no problem including large files.

The source code and the packaged program are here

download or Gitee

Guess you like

Origin blog.csdn.net/weixin_43165220/article/details/130898344