简体   繁体   English

文件夹监视器Java代码两次打印报告

[英]Folder monitor Java code prints report twice

Using some answers from this site I created a small Folder Monitor app in Java. 使用该站点的一些答案,我用Java创建了一个小型Folder Monitor应用程序。 It is supposed to check for changes to a specific folder and output those changes to a text file. 应该检查对特定文件夹的更改,并将这些更改输出到文本文件。 Unfortunately it prints the report twice for every change. 不幸的是,每次更改它都会两次打印报告。 The problem is I cannot figure out where the first line of the report comes from. 问题是我无法弄清楚报告第一行来自何处​​。 Please help me understand what am I doing wrong. 请帮助我了解我在做什么错。

Please find the code below. 请在下面找到代码。 I removed part of the code as it does not affect the Q&A. 我删除了部分代码,因为它不影响问答。

import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class FolderMonitor {

    public FolderMonitor() {}

    //path to a folder you are monitoring
    public static final String FOLDER = "D:\\WatchedDir";

    public static void main(String[] args) throws Exception 
    {
        System.out.println("monitoring started");
        // The monitor will perform polling on the folder every 5 seconds
        final long pollingInterval = 6 * 1000;

        // Let's get a directory as a File object and sort all its files.
        File folderToMonitor = new File(FOLDER);
        File outputFile = new File("H:\\Dir_changes.txt");          

        if (!folderToMonitor.exists()) 
        {
            // Test to see if monitored folder exists
            throw new RuntimeException("Directory not found: " + FOLDER);
        }           

        FileAlterationObserver observer = new FileAlterationObserver(folderToMonitor);
        FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
        FileAlterationListener listener = new FileAlterationListenerAdaptor() 
        {           
            // Is triggered when a file in the monitored folder is modified from 
            @Override
            public void onFileChange(File file) 
            {
                // "file" is the reference to the newly created file                
                try {writeToFile(outputFile, convertLongToDate(outputFile.lastModified()), ("File modified: "+ file.getCanonicalPath()));}               
                    catch (IOException e) {e.printStackTrace();} 
            }           
        };

        observer.addListener(listener);
        monitor.addObserver(observer);
        monitor.start();
    }

    private static void writeToFile(File filePath, String timeStamp, String caughtChange) throws IOException
    {
        FileWriter fileWriter = new FileWriter(filePath,true);

        BufferedWriter bufferFileWriter  = new BufferedWriter(fileWriter);

        fileWriter.append("\r" + timeStamp + " - " + caughtChange + "\r");

        bufferFileWriter.close();     
    }

    private static String convertLongToDate(long input)
    {
        Date date = new Date(input);
        Calendar cal = new GregorianCalendar();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd hh:mm:ss z");
        sdf.setCalendar(cal);
        cal.setTime(date);
        return sdf.format(date);
    }
}

The output looks like this: 输出看起来像这样:

1454622374878 File modified: D:\\WatchedDir\\second\\inside3.txt 2016/Feb/04 04:46:25 EST - File modified: D:\\WatchedDir\\second\\inside3.txt 1454622374878修改文件:D:\\ WatchedDir \\ second \\ inside3.txt 2016 / Feb / 04 04:46:25 EST-修改文件:D:\\ WatchedDir \\ second \\ inside3.txt

I can not figure out where the highlighted (bold) part comes from and how to get rid of it. 我不知道突出显示(粗体)部分来自何处以及如何摆脱它。 Please help! 请帮忙!

I ran the same code that you posted and don't see the extra output in the .txt file. 我运行了与您发布的代码相同的代码,但在.txt文件中看不到多余的输出。 can you please try it by directing the output to a new file and see if it makes any difference 您可以通过将输出定向到新文件来尝试一下,看看是否有任何区别

For some reason Eclipse was executing code that I have already removed from the class and saved the changes. 由于某种原因,Eclipse正在执行我已经从类中删除并保存更改的代码。

After I have restarted Eclipse and executed the code again, everything was running fine (surprise). 重新启动Eclipse并再次执行代码后,一切运行正常(意外)。

I considered deleting this post but I decided to leave it just in case someone will be looking for such a piece of code. 我曾考虑删除此帖子,但我决定将其保留,以防万一有人要查找这样的代码。 I will leave it to the moderators to decide if this question should be deleted. 我将由主持人决定是否应删除此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM