문제

파일 시스템에서 파일이 변경되었을 때 알림을 받고 싶습니다. 나는 마지막으로 수정 된 파일 속성을 조사하는 스레드 만 발견했으며 분명히이 솔루션은 최적이 아닙니다.

도움이 되었습니까?

해결책

낮은 수준 에서이 유틸리티를 모델링하는 유일한 방법은 디렉토리에서 스레드 폴링을하고 파일의 속성에 대한 시계를 유지하는 것입니다. 그러나 패턴을 사용하여 그러한 유틸리티를위한 어댑터를 개발할 수 있습니다.

예를 들어 Tomcat 및 기타 J2EE 애플리케이션 서버에는 배포 디스크립터가 변경되거나 서블릿 클래스가 변경되는 즉시 애플리케이션이 다시 시작되는 자동로드 기능이 있습니다.

대부분의 Tomcat 코드가 재사용 가능하고 OpenSource이므로 해당 서버의 라이브러리를 사용할 수 있습니다.

다른 팁

이전에 로그 파일 모니터를 작성했으며 단일 파일의 속성을 폴링하는 시스템 성능에 미치는 영향이 실제로 매우 작습니다.

Nio.2의 일부로 Java 7, WatchService API

WatchService API는 파일 변경 이벤트에 대해 알리는 응용 프로그램을 위해 설계되었습니다.

Apache Commons의 VFS API를 사용합니다. 다음은 성능에 큰 영향을 미치지 않고 파일을 모니터링하는 방법의 예입니다.

DefaultFilemonitor

lib가 있습니다 Jnotify 그 랩 Inotify Linux에서도 Windows를 지원합니다. 그것을 사용하지 않았고 그것이 얼마나 좋은지 모르겠지만 시도해 볼 가치가 있습니다.

Java Commons-Io는 a FileTerationObserver. 그것은 파일링 모니터와 함께 폴링합니다. Commons VFS와 유사합니다. Advantag는 종속성이 훨씬 적다는 것입니다.

편집 : 적은 종속성은 사실이 아니며 VFS의 선택 사항입니다. 그러나 VFS 추상화 레이어 대신 Java 파일을 사용합니다.

"더 많은 NIO 기능"에는 파일 시계 기능이 있으며 구현은 기본 OS에 따라 다릅니다. JDK7에 있어야합니다.

속성 파일을 읽을 때 마다이 코드 스 니펫을 실행하고, 마지막으로 읽은 이후 수정 된 경우 파일을 실제로 읽습니다. 이것이 누군가를 돕기를 바랍니다.

private long timeStamp;
private File file;

private boolean isFileUpdated( File file ) {
  this.file = file;
  this.timeStamp = file.lastModified();

  if( this.timeStamp != timeStamp ) {
    this.timeStamp = timeStamp;
    //Yes, file is updated
    return true;
  }
  //No, file is not updated
  return false;
}

LOG4J에서도 유사한 접근법이 사용됩니다 FileWatchdog.

Filereader를 사용하여 파일 변경을들을 수 있습니다. plz 아래의 예를 참조하십시오

// File content change listener 
private String fname;
private Object lck = new Object();
... 
public void run()
{
    try
    {
        BufferedReader br = new BufferedReader( new FileReader( fname ) );
        String s;
        StringBuilder buf = new StringBuilder();
        while( true )
        {
            s = br.readLine();
            if( s == null )
            {
                synchronized( lck )
                {
                    lck.wait( 500 );
                }
            }
            else
            {
               System.out.println( "s = " + s );
            }

        }
    }
    catch( Exception e )
    {
        e.printStackTrace();
    }
}

돈을 기꺼이 나누고 싶다면 JniWrapper는 Winpack이있는 유용한 라이브러리입니다. 특정 파일에서 파일 시스템 이벤트를 얻을 수 있습니다. 불행히도 창문 만.

보다 https://www.teamdev.com/jniwrapper.

그렇지 않으면, 기본 코드에 의지하는 것이 특히 제공되는 최고의 제안이 기본 이벤트에 대한 폴링 메커니즘 일 때 항상 나쁜 것은 아닙니다.

일부 컴퓨터에서는 Java 파일 시스템 작업이 느려질 수 있으며 잘 처리되지 않으면 응용 프로그램의 성능에 쉽게 영향을 줄 수 있음을 알았습니다.

Apache Commons JCI (Java Compiler Interface)를 고려할 수도 있습니다. 이 API는 클래스의 동적 컴파일에 중점을 두는 것처럼 보이지만 파일 변경을 모니터링하는 API의 클래스도 포함됩니다.

예시:http://commons.apache.org/jci/usage.html

Spring Integration은 디렉토리와 파일을 시청하는 좋은 메커니즘을 제공합니다. http://static.springsource.org/spring-integration/reference/htmlsingle/#files. 크로스 플랫폼인지 확인합니다 (Mac, Linux 및 Windows에서 사용했습니다).

JXFileWatcher라는 파일 및 폴더를위한 상용 크로스 데스크 탑 라이브러리가 있습니다. 여기에서 다운로드 할 수 있습니다.http://www.teamdev.com/jxfilewatcher/

또한 온라인으로 행동 할 수 있습니다. http://www.teamdev.com/jxfilewatcher/onlinedemo/

폴링 마지막 수정 된 파일 속성은 간단하면서도 효과적인 솔루션입니다. 내 확장 된 클래스를 정의하십시오 FileChangedWatcher 그리고 구현 onModified() 방법:

import java.io.File;

public abstract class FileChangedWatcher
{
    private File file;

    public FileChangedWatcher(String filePath)
    {
        file = new File(filePath);
    }

    public void watch() throws InterruptedException
    {
        long currentModifiedDate = file.lastModified();

        while (true)
        {
            long newModifiedDate = file.lastModified();

            if (newModifiedDate != currentModifiedDate)
            {
                currentModifiedDate = newModifiedDate;
                onModified();
            }

            Thread.sleep(100);
        }
    }

    public String getFilePath()
    {
        return file.getAbsolutePath();
    }

    protected abstract void onModified();
}

다른 답변과 마찬가지로 여기에 파일, 타이머 및 타이머 스탁을 사용하여 설정 한 방법이 설정되어 설정 간격으로 배경 스레드 폴링으로 실행되도록합니다.

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class FileModifiedWatcher
{
  private static File file;
  private static int pollingInterval;
  private static Timer fileWatcher;
  private static long lastReadTimeStamp = 0L;

  public static boolean init(String _file, int _pollingInterval)
  {
    file =  new File(_file);
    pollingInterval = _pollingInterval; // In seconds

    watchFile();

    return true;
  }

  private static void watchFile()
  {
    if ( null == fileWatcher )
    {
      System.out.println("START");

      fileWatcher = new Timer();

      fileWatcher.scheduleAtFixedRate(new TimerTask()
      {
        @Override
        public void run()
        {

          if ( file.lastModified() > lastReadTimeStamp )
          {
            System.out.println("File Modified");
          }

          lastReadTimeStamp = System.currentTimeMillis();
        }
      }, 0, 1000 * pollingInterval);
    }

  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top