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

时间:2016-02-05 15:23:58

标签: java directory monitoring

使用本网站的一些答案,我用Java创建了一个小型的Folder Monitor应用程序。它应该检查特定文件夹的更改并将这些更改输出到文本文件。不幸的是,它会为每次更改打印两次报告。问题是我无法弄清楚报告的第一行来自哪里。请帮我理解我做错了什么。

请找到以下代码。我删除了部分代码,因为它不影响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);
    }
}

输出如下:

  

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

我无法弄清楚突出显示的(粗体)部分来自何处以及如何摆脱它。请帮忙!

2 个答案:

答案 0 :(得分:1)

我运行了您发布的相同代码,但没有在.txt文件中看到额外的输出。你能不能通过将输出定向到一个新文件来看看它是否有任何区别

答案 1 :(得分:0)

出于某种原因,Eclipse正在执行我已从类中删除并保存更改的代码。

在我重新启动Eclipse并再次执行代码后,一切运行正常(惊喜)。

我考虑过删除这篇文章,但我决定离开它以防万一有人会寻找这样的代码。我将把它留给主持人来决定是否应该删除这个问题。