FileWatchTest.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import org.apache.commons.io.IOUtils;
  2. import org.junit.After;
  3. import org.junit.Test;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import java.io.*;
  7. import java.nio.file.*;
  8. import java.util.List;
  9. import java.util.concurrent.TimeUnit;
  10. /**
  11. * @author AE86
  12. * @version 1.0.0
  13. * @date 2022/5/6 21:32
  14. */
  15. public class FileWatchTest {
  16. private final Logger logger = LoggerFactory.getLogger(getClass());
  17. private String path = "d:/test/";
  18. private WatchService watchService;
  19. @After
  20. public void close() throws IOException {
  21. if (null != watchService) {
  22. watchService.close();
  23. }
  24. }
  25. @Test
  26. public void testFileWatch() throws IOException, InterruptedException {
  27. watchService = FileSystems.getDefault().newWatchService();
  28. Path p = Paths.get(path);
  29. p.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
  30. logger.info("启动监听");
  31. long count = 0L;
  32. while (count < 30) {
  33. WatchKey watchKey = watchService.take();
  34. List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
  35. for (WatchEvent<?> event : watchEvents) {
  36. Object context = event.context();
  37. logger.info("[{}{}] 文件发生了[{}]事件", path, context, event.kind());
  38. }
  39. watchKey.reset();
  40. TimeUnit.SECONDS.sleep(1);
  41. count++;
  42. }
  43. }
  44. @Test
  45. public void testReadFile() {
  46. read(path + "test.txt");
  47. }
  48. private void read(String file) {
  49. RandomAccessFile raf = null;
  50. byte[] buffer = new byte[4096];
  51. try {
  52. raf = new RandomAccessFile(file, "r");
  53. raf.seek(raf.length());
  54. logger.info("offset:{}", raf.getFilePointer());
  55. while (true) {
  56. int len = raf.read(buffer);
  57. if (-1 != len) {
  58. logger.info("offset:{}, len:{}", raf.getFilePointer(), len);
  59. logger.info(new String(buffer, 1, len, "UTF-8"));
  60. }
  61. TimeUnit.SECONDS.sleep(1);
  62. }
  63. } catch (IOException e) {
  64. logger.error(e.getMessage());
  65. } catch (InterruptedException e) {
  66. logger.error(e.getMessage());
  67. } finally {
  68. IOUtils.closeQuietly(raf);
  69. }
  70. }
  71. }