2017-01-03 1 views
0

새 폴더 및 파일 작성을위한 루트 디렉토리와 하위 디렉토리에 대한 Java 감시 서비스를 개발 중입니다. 내 루트 디렉토리는 C:/REST API/source/입니다. 여기처럼 보일 수 있습니다 만 루트 디렉토리가 기본적으로 생성 및 서브 디렉토리가 최종 사용자에 의해 생성 된 나의 폴더 구조입니다

사용자 작업시 감시자 서비스 기반 변경

C:/REST API/source/ 
    - /source/new folder 
    -/source/new folder/new folder 
    -/source/new folder(2) 

가있다 감지 않다면, 루트 디렉토리로 C:/REST API/source/을 등록합니다 내 프로그램 C:/REST API/source/에 생성 된 새 폴더는 C:/REST API/source/new folder 경로를 등록합니다. 동일한 프로세스가 /source/new folder/new folder으로 테스트되며 잘 작동합니다. 나는 다시 내 루트 디렉토리입니다 /source/ 디렉토리 아래에 새 폴더를 만들려고 할 때, 나는 경로가 올바르지 않습니다 발견

이는 수 다시 등록하는 것입니다 내 컴파일러 문

1 
2 
3 
a 
b 
C:\REST API\source 
c 
d 
e 
C:\REST API\source 
4 
5 
6 
7 
8 
9 
New folder 
C:\REST API\source\New folder 
file:///C:/REST%20API/source/New%20folder/ 
10 
C:\REST API\source\New folder 
11 
12 
13 
aa 
bb 
C:\REST API\source\New folder 
cc 
dd 
ee 
14 
C:\REST API\source\New folder 

The new file :C:\REST API\source\New folderEvent :ENTRY_CREATE 
5 
6 
7 
8 
9 
New folder 
C:\REST API\source\New folder\New folder 
file:///C:/REST%20API/source/New%20folder/New%20folder/ 
10 
C:\REST API\source\New folder\New folder 
11 
12 
13 
aa 
bb 
C:\REST API\source\New folder\New folder 
cc 
dd 
ee 
14 
C:\REST API\source\New folder\New folder 

The new file :C:\REST API\source\New folder\New folderEvent :ENTRY_CREATE 
5 
6 
7 
8 
9 
New folder (2) 
C:\REST API\source\New folder\New folder\New folder (2) 
file:///C:/REST%20API/source/New%20folder/New%20folder/New%20folder%20(2) 
10 
C:\REST API\source\New folder\New folder\New folder (2) 
11 

The new file :C:\REST API\source\New folder\New folder\New folder (2)Event :ENTRY_CREATE 
5 



입니다 루트 디렉토리 또는 사용자가 어떤 디렉토리에 액세스했는지 탐지하므로, 이전에 사용자가 현재 디렉토리를 작성한 경우에는 감시자 서비스가 사용자에 의한 현재 디렉토리 액세스에 다시 등록됩니다. 왜냐하면 내가 뭘 발견했는지는 path=child에 의한 것이기 때문입니다. 내가 경로 변수로 아이를 덮어 쓰지 않았다면 나는 모니터링 디렉토리

public class fileStatus { 

    public static void main(String [] args) throws FileNotFoundException, IOException, JSONException, InterruptedException 
    { 
    try(WatchService svc = FileSystems.getDefault().newWatchService()) 
     { 
     System.out.println("1"); 
      Map<WatchKey, Path> keyMap = new HashMap<>(); 
      System.out.println("2"); 
      Path path = Paths.get("C:/REST API/source/"); 
      System.out.println("3"); 
      fileStatus.registerAll(path,keyMap,svc); 
      System.out.println(path); 
      System.out.println("4"); 
      WatchKey wk ; 
      do 
      { 
       System.out.println("5"); 
       wk = svc.take(); 
       System.out.println("6"); 
       for(WatchEvent<?> event : wk.pollEvents()) 
       { 
        System.out.println("7"); 
        WatchEvent.Kind<?> type = event.kind(); 
        System.out.println("8"); 
        Path fileName = (Path)event.context(); 
        System.out.println("9"); 
        System.out.println(fileName); 
        Path child = path.resolve(fileName); 
        URI uri = child.toUri(); 
        System.out.println(child); 
        System.out.println(uri); 
        System.out.println("10"); 
        Path newPath = Paths.get(uri);    
        System.out.println(newPath); 

        System.out.println("11"); 
        if (Files.isDirectory(newPath, LinkOption.NOFOLLOW_LINKS)) 
        { 
         System.out.println("12"); 
         if(type == StandardWatchEventKinds.ENTRY_CREATE) 
         { 
          System.out.println("13"); 
          register(newPath,keyMap,svc); 
          System.out.println("14"); 
          System.out.println(newPath); 
          child=newPath; 
         } 
        } 
        System.out.println("\nThe new file :"+child+ "Event :" +type); 
        path = child ; 

       } 
      }while(wk.reset()); 
     } 
    catch(IOException e) 
    { 
     e.printStackTrace(); 
    } 

    } 

    private static Path register(Path newPath, Map<WatchKey, Path> keyMap, WatchService svc) throws IOException 
    { 
     System.out.println("aa"); 
     Files.walkFileTree(newPath,new SimpleFileVisitor<Path>() 
     { 

      public FileVisitResult preVisitDirectory(Path newPath, BasicFileAttributes attrs) throws IOException 
      { 
       System.out.println("bb"); 
       System.out.println(newPath); 
       if(attrs.isDirectory()) 
       { 
        System.out.println("cc"); 
        keyMap.put(newPath.register(svc, StandardWatchEventKinds.ENTRY_CREATE),newPath); 
       } 
       System.out.println("dd"); 
       return FileVisitResult.CONTINUE; 
      } 
     }); 
     System.out.println("ee"); 
return newPath; 

    } 

    private static Path registerAll(Path path, Map<WatchKey, Path> keyMap, WatchService svc) throws IOException 
    { 
     System.out.println("a"); 
     Files.walkFileTree(path,new SimpleFileVisitor<Path>() 
       { 

        public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs) throws IOException 
        { 
         System.out.println("b"); 
         System.out.println(path); 
         if(attrs.isDirectory()) 
         { 
          System.out.println("c"); 
          keyMap.put(path.register(svc, StandardWatchEventKinds.ENTRY_CREATE),path); 
         } 
         System.out.println("d"); 
         return FileVisitResult.CONTINUE; 
        } 
       }); 
     System.out.println("e"); 
     return path; 
    } 

} 

답변

1
에 파일을 넣으면, 내가 파일 경로를 다시 검색 할 수 없습니다입니다

코드와 문제는 path가 있다는 것이다 while 루프의 끝에 child으로 설정하십시오. 그것은

  1. 디렉토리 a/은 기본적으로 추적되는 경우, 경로를 a 다음 디렉토리 a/b/가 생성되고 경로가 a/b/ 다음 디렉토리 a/c/가 생성됩니다
  2. 로 설정되어
  3. 로 설정되어 있다는 것을 의미한다. (Path) event.context()에서 c을 반환합니다. 그러나 다음 코드 path.resolve(fileName)에 의해 경로 a/b/과 일치합니다. 그것은 당신을 제공 a/b/c/ 대신 a/c

의 불행하게도 WatchService가 이벤트를 채워 directory을 얻을 수 없습니다. 모든 기존/새 디렉토리에 대해 별도의 WatchService을 만들 수 있지만 과도 할 수 있습니다.

특수 Sun 클래스 인 ExtendedWatchEventModifier.FILE_TREE을 사용하여 모든 하위 디렉토리가있는 디렉토리를 추적하도록 제안합니다. 이 경우 a이 추적되고 a/b/c이 생성되면 WatchEvent에서 얻은 Pathb/c이되고 루트 경로를 사용하여 해결할 수 있습니다. 아래의 대략적인 코드를 참조하십시오 :

import com.sun.nio.file.ExtendedWatchEventModifier; 
import org.json.JSONException; 

import java.io.IOException; 
import java.net.URI; 
import java.nio.file.*; 
import java.nio.file.attribute.BasicFileAttributes; 

public class fileStatus { 

    public static void main(String[] args) throws IOException, JSONException, InterruptedException { 
     try (WatchService svc = FileSystems.getDefault().newWatchService()) { 
      final Path path = Paths.get("C:/ADovzhenko/watch_dir"); 
      registerAll(path, svc); 
      WatchKey wk; 
      do { 
       wk = svc.take(); 
       for (WatchEvent<?> event : wk.pollEvents()) { 
        WatchEvent.Kind<?> type = event.kind(); 
        Path child = path.resolve((Path) event.context()); 
        URI uri = child.toUri(); 
        System.out.println("Created: " + child); 
       } 
      } while (wk.reset()); 
     } 
    } 

    private static Path registerAll(Path path, final WatchService svc) throws IOException { 
     //Register folder and its sub-folders 
     path.register(svc, new WatchEvent.Kind<?>[]{StandardWatchEventKinds.ENTRY_CREATE}, ExtendedWatchEventModifier.FILE_TREE); 

     //Print all existing directories 
     Files.walkFileTree(path, new SimpleFileVisitor<Path>() { 
      public FileVisitResult preVisitDirectory(final Path dir, BasicFileAttributes attrs) throws IOException { 
       if (attrs.isDirectory()) { 
        System.out.println("Existing: " + dir); 
        return FileVisitResult.CONTINUE; 
       } 
       //In case if print of non-directory is required 
       //System.out.println("Existing: " + dir); 
       return FileVisitResult.SKIP_SIBLINGS; 
      } 
     }); 
     return path; 
    } 

} 
+0

등록 방법으로 ExtendedWatchEventModifier.FILE_TREE를 인수로 사용합니까? 내가 아는 것은 그것이 지원되지 않을 수도 있다는 것이다. – yumi

+0

이것은 Windows 플랫폼에서만 지원되지만'C : /'파일 경로로 인해 Windows를 사용한다고 가정한다. –

+0

은 ExtendedWatchEventModifier.FILE_TREE register()의 유효한 인수입니까?path.register (svc, new WatchEvent.Kind [] {StandardWatchEventKinds.ENTRY_CREATE}, ExtendedWatchEventModifier.FILE_TREE)를 사용하려고하면 컴파일러에서 오류가 발생하기 때문에 반환됩니다. , ExtendedWatchEventModifier.FILE_TREE가 register() 메소드에 할당 할 수없는 것처럼 보입니다. – yumi