|
3 | 3 |
|
4 | 4 | === WatchService |
5 | 5 |
|
6 | | -.Objetivo |
| 6 | +.Objective |
7 | 7 | -------------------------------------------------- |
8 | 8 | Observe the changes in a directory by using the WatchService interface |
9 | | -- |
10 | | -Observar as mudanças em um diretório a partir da utilização da Interface WatchService |
11 | 9 | -------------------------------------------------- |
12 | 10 |
|
13 | | -O WatchService é uma API para monitorar mudanças em arquivos e diretórios. Serão apresentadas as principais formas de realizar essa monitoração. |
| 11 | +WatchService is an API for monitoring file and directory changes. The main ways to carry out this monitoring will be presented. |
14 | 12 |
|
15 | | -Para utilizar a API são necessárias 4 classes principais: |
| 13 | +To use the API you need 4 main classes: |
16 | 14 |
|
17 | | -* WatchService -> representa o serviço em si de monitoração; |
18 | | -* StandardWatchEventKinds -> representa os tipos de alteração que se deseja monitorar: criar, apagar ou modificar; |
19 | | -* WatchKey -> representa um retorno do serviço informando que houveram alterações; |
20 | | -* WatchEvent -> representa um evento em si, onde é possível obter informações do que foi alterado. |
| 15 | +* WatchService -> represents the monitoring service itself; |
| 16 | +* StandardWatchEventKinds -> represents the types of changes you want to monitor: create, delete or modify; |
| 17 | +* WatchKey -> represents a return of the service informing that there have been changes; |
| 18 | +* WatchEvent -> represents an event itself, where you can get information about what has changed. |
21 | 19 |
|
22 | | -//- |
| 20 | +// - |
23 | 21 |
|
24 | | -. É possível observar criações ou deleções de arquivos em um diretório. |
| 22 | +. You can observe file creations or deletions in a directory. |
25 | 23 | + |
26 | 24 | [source,java,indent=0] |
27 | 25 | .{java-package}/watchservice/WatchService_CreateDelete.java |
28 | 26 | ---- |
29 | 27 | include::{section-java-package}/watchservice/WatchService_CreateDelete.java[tag=code] |
30 | 28 | ---- |
31 | 29 | + |
32 | | -.Saída no console |
| 30 | +.console output |
33 | 31 | [source,console] |
34 | 32 | ---- |
35 | | -Path: /home/rinaldo/arquivos |
36 | | -Eventos capturados. Quantidade: 1 |
37 | | -Evento ocorrido. Tipo : ENTRY_DELETE. Contexto: arquivo1.txt |
38 | | -Eventos capturados. Quantidade: 1 |
39 | | -Evento ocorrido. Tipo : ENTRY_CREATE. Contexto: arquivo1.txt |
| 33 | +Path: /home/rinaldo/files |
| 34 | +Events captured. Quantity: 1 |
| 35 | +Event occurred. Type: ENTRY_DELETE. Context: file1.txt |
| 36 | +Events captured. Quantity: 1 |
| 37 | +Event occurred. Type: ENTRY_CREATE. Context: file1.txt |
40 | 38 | ---- |
41 | 39 | + |
42 | | -Isso é o que seria impresso no console caso o `arquivo1.txt` fosse apagado e depois criado novamente. |
| 40 | +This is what would be printed on the console if `file1.txt` were deleted and then created again. |
43 | 41 | + |
44 | | -Perceba os passos que foram feitos: |
| 42 | +Note the steps that were taken: |
45 | 43 | + |
46 | | -.. Um WatchService foi criado |
47 | | -.. O service foi registrado no `Path` com os eventos desejados |
48 | | -.. Foi criado um _loop_ infinito para realizar a monitoração de forma contínua |
49 | | -.. Foi chamado o método `take`, que aguarda até haver eventos e assim, retorná-los |
50 | | -.. Foi chamado o método `pollEvents` para recuperar os eventos que ocorreram |
51 | | -.. Os eventos foram impressos no console |
52 | | -.. O `WatchKey` foi resetado para que pudesse ser utilizado novamente |
| 44 | +.. A WatchService has been created. |
| 45 | +.. The service has been registered in `Path` with the desired events. |
| 46 | +.. An infinite _loop_ has been created to continuously monitor. |
| 47 | +.. The `take` method was called, which waits until there are events and thus returns them. |
| 48 | +.. The `pollEvents` method was called to retrieve events that occurred. |
| 49 | +.. Events were printed on console. |
| 50 | +.. WatchKey has been reset so that it can be used again. |
53 | 51 |
|
54 | 52 | + |
55 | | -Esse é o básico de um `WatchService`. Perceba que ele é um recurso que deve ser fechado, por isso está na sintaxe de `try-with-resources`. |
| 53 | +This is the basics of a `WatchService`. Note that it is a resource that must be closed, so it is in the `try-with-resources` syntax. |
56 | 54 |
|
57 | | -. É possível monitorar mudanças em arquivos de um diretório. |
| 55 | +. You can monitor changes to files in a directory. |
58 | 56 | + |
59 | 57 | [source,java,indent=0] |
60 | 58 | .{java-package}/watchservice/WatchService_Modify.java |
61 | 59 | ---- |
62 | 60 | include::{section-java-package}/watchservice/WatchService_Modify.java[tag=code] |
63 | 61 | ---- |
64 | 62 | + |
65 | | -.Saída no console |
| 63 | +.console output |
66 | 64 | [source,console] |
67 | 65 | ---- |
68 | | -Path: /home/rinaldo/arquivos |
69 | | -Eventos capturados. Quantidade: 1 |
70 | | -Evento ocorrido. Tipo : ENTRY_MODIFY. Contexto: .arquivo1.txt.kate-swp |
71 | | -Eventos capturados. Quantidade: 1 |
72 | | -Evento ocorrido. Tipo : ENTRY_MODIFY. Contexto: arquivo1.txt.h26197 |
73 | | -Eventos capturados. Quantidade: 1 |
74 | | -Evento ocorrido. Tipo : ENTRY_MODIFY. Contexto: arquivo1.txt.h26197 |
| 66 | +Path: /home/rinaldo/files |
| 67 | +Events captured. Quantity: 1 |
| 68 | +Event occurred. Type: ENTRY_MODIFY. Context: .file1.txt.kate-swp |
| 69 | +Events captured. Quantity: 1 |
| 70 | +Event occurred. Type: ENTRY_MODIFY. Context: file1.txt.h26197 |
| 71 | +Events captured. Quantity: 1 |
| 72 | +Event occurred. Type: ENTRY_MODIFY. Context: file1.txt.h26197 |
75 | 73 | ---- |
76 | 74 | + |
77 | | -Esses foram os eventos que ocorreram ao abrir o `arquivo1.txt` com o editor `Kate`, acrescentar um caracter, e salvar o arquivo. |
| 75 | +These were the events that occurred when opening `file1.txt` with the `Kate` editor, adding a character, and saving the file. |
78 | 76 |
|
79 | | -. Não é possível monitorar diretamente um arquivo. |
| 77 | +. Unable to monitor a file directly. |
80 | 78 | + |
81 | 79 | [source,java,indent=0] |
82 | 80 | .{java-package}/watchservice/WatchService_File.java |
83 | 81 | ---- |
84 | 82 | include::{section-java-package}/watchservice/WatchService_File.java[tag=code] |
85 | 83 | ---- |
86 | 84 | + |
87 | | -.Saída no console |
| 85 | +.console output |
88 | 86 | [source,console] |
89 | 87 | ---- |
90 | | -Path: /home/rinaldo/arquivos/arquivo1.txt |
91 | | -java.nio.file.NotDirectoryException: /home/rinaldo/arquivos/arquivo1.txt |
| 88 | +Path: /home/rinaldo/files/file1.txt |
| 89 | +java.nio.file.NotDirectoryException: /home/rinaldo/files/file1.txt |
92 | 90 | at sun.nio.fs.LinuxWatchService$Poller.implRegister(LinuxWatchService.java:249) |
93 | 91 | at sun.nio.fs.AbstractPoller.processRequests(AbstractPoller.java:260) |
94 | 92 | at sun.nio.fs.LinuxWatchService$Poller.run(LinuxWatchService.java:364) |
95 | 93 | at java.lang.Thread.run(Thread.java:748) |
96 | 94 | ---- |
97 | 95 | + |
98 | | -Perceba que ocorre exceção ao tentar monitorar diretamente o `arquivo1.txt`. |
| 96 | +Note that exception occurs when trying to directly monitor `file1.txt`. |
99 | 97 |
|
100 | | -. É possível recuperar um `WatchKey` imediatamente ou aguardar um período específico com os métodos `poll`. |
| 98 | +. You can retrieve a `WatchKey` immediately or wait for a specific period with `poll` methods. |
101 | 99 | + |
102 | 100 | [source,java,indent=0] |
103 | 101 | .{java-package}/watchservice/WatchService_Poll.java |
104 | 102 | ---- |
105 | 103 | include::{section-java-package}/watchservice/WatchService_Poll.java[tag=code] |
106 | 104 | ---- |
107 | 105 | + |
108 | | -.Saída no console |
| 106 | +.console output |
109 | 107 | [source,console] |
110 | 108 | ---- |
111 | | -Path: /home/rinaldo/arquivos |
112 | | -Horário antes do poll sem timeout: 14:55:10.298 |
113 | | -WatchKey do poll: null |
114 | | -Horário depois do poll sem timeout: 14:55:10.298 |
115 | | -Horário antes do poll com timeout: 14:55:10.298 |
116 | | -WatchKey do poll com timeout: null |
117 | | -Horário depois do poll com timeout: 14:55:15.300 |
| 109 | +Path: /home/rinaldo/files |
| 110 | +Time before poll without timeout: 14:55:10.298 |
| 111 | +WatchKey's poll: null |
| 112 | +Time after poll without timeout: 14:55:10.298 |
| 113 | +Time before poll with timeout: 14:55:10.298 |
| 114 | +WatchKey's poll with timeout: null |
| 115 | +Time after poll with timeout: 14:55:15.300 |
118 | 116 | ---- |
119 | 117 | + |
120 | | -Perceba que o primeiro `poll` retorna imediatamente, mesmo que nenhum evento tenha ocorrido. Já o segundo aguarda por 5 segundos para retornar, mesmo que não haja evento. |
| 118 | +Note that the first `poll` returns immediately, even if no events have occurred. The second waits for 5 seconds to return, even if there is no event. |
121 | 119 | + |
122 | | -Nos cenários de monitoração, o ideal é utilizar o `take`, caso contrário seria necessário invocar o `poll` inúmeras vezes, enquanto o `take` apenas aguarda indefinidamente até que haja um evento. |
| 120 | +In monitoring scenarios, it is best to use take, otherwise you would need to invoke poll countless times, while take only waits indefinitely until there is an event. |
123 | 121 |
|
| 122 | + |
| 123 | +.References |
124 | 124 | **** |
125 | 125 |
|
126 | 126 | * Monitoring a Directory for Changes |
127 | 127 | + |
128 | | -Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 625). Wiley. Edição do Kindle. |
| 128 | +Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 625). Wiley. Kindle Edition. |
129 | 129 |
|
130 | 130 | * https://www.baeldung.com/java-nio2-watchservice[A Guide to WatchService in Java NIO2.] |
131 | 131 |
|
132 | 132 | * https://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html[Class Files.] Java Plataform SE 7. |
133 | 133 |
|
134 | 134 | * https://docs.oracle.com/javase/tutorial/essential/io/notification.html[Watching a Directory for Changes.] The Java™ Tutorials. |
135 | 135 |
|
136 | | -**** |
| 136 | +**** |
0 commit comments