2017-04-18 66 views
2

這裏擴展問題:重新啓動春季開機的時候輸入文本文件的更改

Reading data from file at start to use in controller in Spring Boot

我希望我的春天啓動應用程序重新啓動生產的輸入文件發生更改時。我將啓動應用程序像這樣的東西

java -jar application.jar [filename] 

當我修改輸入的文本文件,應用程序必須重新啓動,並再次讀取該文件。我該怎麼做?我在問如何觀察文件更改並觸發重啓。

+0

可能重複的[以編程方式重新啓動Spring Boot應用程序](http://stackoverflow.com/questions/29117308/programmatically-restart-spring-boot-application) –

回答

2

解決方案使用shell腳本

我會建議監視使用文件觀察家輸入文件,如果有任何文件更改檢測,你可以使用shell腳本重新啓動應用程序。

您沒有提供平臺信息。

如果你的產品是在Linux上,那麼你可以使用watch監視輸入文件 變化。

解決方案使用Java

如果要檢測的Java文件的變化,你可以使用FileWatcher,

final Path path = FileSystems.getDefault().getPath(System.getProperty("user.home"), "Desktop"); 
System.out.println(path); 
try{ 
    final WatchService watchService = FileSystems.getDefault().newWatchService(); 
    final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); 
    while (true) { 
     final WatchKey wk = watchService.take(); 
     for (WatchEvent<?> event : wk.pollEvents()) { 
      //we only register "ENTRY_MODIFY" so the context is always a Path. 
      final Path changed = (Path) event.context(); 
      System.out.println(changed); 
      if (changed.endsWith("myFile.txt")) { 
       System.out.println("My file has changed"); 
      } 
     } 
     // reset the key 
     boolean valid = wk.reset(); 
     if (!valid) { 
      System.out.println("Key has been unregisterede"); 
     } 
    } 
} 

我們從Java中重新啓動應用程序,你必須從您的主要方法中啓動您的應用程序。

創建一個單獨的線程,該線程將監視您的輸入文件,並在單獨的線程中啓動您的應用程序。

每當您檢測到輸入文件發生任何變化時,中斷或終止應用程序線程,然後在新線程中重新啓動應用程序。

+0

是的,它是Ubuntu的16.04,但我必須在程序內部本身 – uploader33

+0

在Java中,您可以使用FileWatcher API檢測文件更改 –