Skip to content

Commit 492aee3

Browse files
committed
feat(file-io): 🎸 watch service, translated
Refers: #9
1 parent b74123d commit 492aee3

File tree

5 files changed

+91
-91
lines changed

5 files changed

+91
-91
lines changed

book/07-file-io/sections/05-watch-service.asc

Lines changed: 55 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -3,134 +3,134 @@
33

44
=== WatchService
55

6-
.Objetivo
6+
.Objective
77
--------------------------------------------------
88
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
119
--------------------------------------------------
1210

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.
1412

15-
Para utilizar a API são necessárias 4 classes principais:
13+
To use the API you need 4 main classes:
1614

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.
2119

22-
//-
20+
// -
2321

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.
2523
+
2624
[source,java,indent=0]
2725
.{java-package}/watchservice/WatchService_CreateDelete.java
2826
----
2927
include::{section-java-package}/watchservice/WatchService_CreateDelete.java[tag=code]
3028
----
3129
+
32-
.Saída no console
30+
.console output
3331
[source,console]
3432
----
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
4038
----
4139
+
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.
4341
+
44-
Perceba os passos que foram feitos:
42+
Note the steps that were taken:
4543
+
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.
5351

5452
+
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.
5654

57-
. É possível monitorar mudanças em arquivos de um diretório.
55+
. You can monitor changes to files in a directory.
5856
+
5957
[source,java,indent=0]
6058
.{java-package}/watchservice/WatchService_Modify.java
6159
----
6260
include::{section-java-package}/watchservice/WatchService_Modify.java[tag=code]
6361
----
6462
+
65-
.Saída no console
63+
.console output
6664
[source,console]
6765
----
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
7573
----
7674
+
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.
7876

79-
. Não é possível monitorar diretamente um arquivo.
77+
. Unable to monitor a file directly.
8078
+
8179
[source,java,indent=0]
8280
.{java-package}/watchservice/WatchService_File.java
8381
----
8482
include::{section-java-package}/watchservice/WatchService_File.java[tag=code]
8583
----
8684
+
87-
.Saída no console
85+
.console output
8886
[source,console]
8987
----
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
9290
at sun.nio.fs.LinuxWatchService$Poller.implRegister(LinuxWatchService.java:249)
9391
at sun.nio.fs.AbstractPoller.processRequests(AbstractPoller.java:260)
9492
at sun.nio.fs.LinuxWatchService$Poller.run(LinuxWatchService.java:364)
9593
at java.lang.Thread.run(Thread.java:748)
9694
----
9795
+
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`.
9997

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.
10199
+
102100
[source,java,indent=0]
103101
.{java-package}/watchservice/WatchService_Poll.java
104102
----
105103
include::{section-java-package}/watchservice/WatchService_Poll.java[tag=code]
106104
----
107105
+
108-
.Saída no console
106+
.console output
109107
[source,console]
110108
----
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
118116
----
119117
+
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.
121119
+
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.
123121

122+
123+
.References
124124
****
125125
126126
* Monitoring a Directory for Changes
127127
+
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.
129129
130130
* https://www.baeldung.com/java-nio2-watchservice[A Guide to WatchService in Java NIO2.]
131131
132132
* https://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html[Class Files.] Java Plataform SE 7.
133133
134134
* https://docs.oracle.com/javase/tutorial/essential/io/notification.html[Watching a Directory for Changes.] The Java™ Tutorials.
135135
136-
****
136+
****

src/org/j6toj8/fileio/watchservice/WatchService_CreateDelete.java

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,25 +15,25 @@ public class WatchService_CreateDelete {
1515
public static void main(String[] args) {
1616
// tag::code[]
1717
String userHome = System.getProperty("user.home");
18-
Path path = Paths.get(userHome, "arquivos");
18+
Path path = Paths.get(userHome, "files");
1919
System.out.println("Path: " + path);
2020

21-
// criação do WatchService - ainda sem monitorar nada
21+
// WatchService creation - still not monitoring anything
2222
try (WatchService service = FileSystems.getDefault().newWatchService();) {
23-
24-
// registro do WatchService no Path para monitorar os evento de CREATE e DELETE
23+
24+
// WatchService log in Path to monitor CREATE and DELETE events
2525
path.register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
2626

27-
while (true) { // loop infinito
28-
// take() irá retornar sempre que houverem eventos
29-
// caso contrário a chamada fica parada esperando eventos ocorrerem
27+
while (true) { // infinite loop
28+
// take() will return whenever there are events
29+
// otherwise the call is stopped waiting for events to occur
3030
WatchKey key = service.take();
31-
List<WatchEvent<?>> pollEvents = key.pollEvents(); // recupera os eventos ocorridos
32-
System.out.println("Eventos capturados. Quantidade: " + pollEvents.size());
33-
for (WatchEvent<?> event : pollEvents) { // iteração sobre todos os eventos recuperados
34-
System.out.println("Evento ocorrido. Tipo : " + event.kind() + ". Contexto: " + event.context());
31+
List<WatchEvent<?>> pollEvents = key.pollEvents(); // recovers events
32+
System.out.println("Events captured. Quantity: " + pollEvents.size());
33+
for (WatchEvent<?> event : pollEvents) { // iteration over all retrieved events
34+
System.out.println("Event occurred. Type: " + event.kind() + ". Context: " + event.context());
3535
}
36-
key.reset(); // reseta o WatchKey para que possa ser utilizado novamente
36+
key.reset(); // resets WatchKey so that it can be used again
3737
}
3838
} catch (IOException | InterruptedException e) {
3939
e.printStackTrace();

src/org/j6toj8/fileio/watchservice/WatchService_File.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ public class WatchService_File {
1212
public static void main(String[] args) {
1313
// tag::code[]
1414
String userHome = System.getProperty("user.home");
15-
Path path = Paths.get(userHome, "arquivos", "arquivo1.txt"); // NÃO SUPORTADO
15+
Path path = Paths.get(userHome, "files", "file1.txt"); // NOT SUPPORTED
1616
System.out.println("Path: " + path);
1717

1818
try (WatchService service = FileSystems.getDefault().newWatchService();) {
19-
path.register(service, StandardWatchEventKinds.ENTRY_MODIFY); // LANÇA EXCEÇÃO
19+
path.register(service, StandardWatchEventKinds.ENTRY_MODIFY); // THROWS EXCEPTION
2020
} catch (IOException e) {
2121
e.printStackTrace();
2222
}

src/org/j6toj8/fileio/watchservice/WatchService_Modify.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,25 +15,25 @@ public class WatchService_Modify {
1515
public static void main(String[] args) {
1616
// tag::code[]
1717
String userHome = System.getProperty("user.home");
18-
Path path = Paths.get(userHome, "arquivos");
18+
Path path = Paths.get(userHome, "files");
1919
System.out.println("Path: " + path);
2020

21-
// criação do WatchService - ainda sem monitorar nada
21+
// WatchService creation - still not monitoring anything
2222
try (WatchService service = FileSystems.getDefault().newWatchService();) {
23-
24-
// registro do WatchService no Path para monitorar o evento de MODIFY
23+
24+
// WatchService log in Path to monitor MODIFY event
2525
path.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
26-
27-
while (true) { // loop infinito
28-
// take() irá retornar sempre que houverem eventos
29-
// caso contrário a chamada fica parada esperando eventos ocorrerem
26+
27+
while (true) { // infinite loop
28+
// take() will return whenever there are events
29+
// otherwise the call is stopped waiting for events to occur
3030
WatchKey key = service.take();
31-
List<WatchEvent<?>> pollEvents = key.pollEvents(); // recupera os eventos ocorridos
32-
System.out.println("Eventos capturados. Quantidade: " + pollEvents.size());
33-
for (WatchEvent<?> event : pollEvents) { // iteração sobre todos os eventos recuperados
34-
System.out.println("Evento ocorrido. Tipo : " + event.kind() + ". Contexto: " + event.context());
31+
List<WatchEvent<?>> pollEvents = key.pollEvents(); // recovers events
32+
System.out.println("Events captured. Quantity: " + pollEvents.size());
33+
for (WatchEvent<?> event : pollEvents) { // iteration over all retrieved events
34+
System.out.println("Event occurred. Type: " + event.kind() + ". Context: " + event.context());
3535
}
36-
key.reset(); // reseta o WatchKey para que possa ser utilizado novamente
36+
key.reset(); // resets WatchKey so that it can be used again
3737
}
3838
} catch (IOException | InterruptedException e) {
3939
e.printStackTrace();

src/org/j6toj8/fileio/watchservice/WatchService_Poll.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,21 @@ public class WatchService_Poll {
1515
public static void main(String[] args) {
1616
// tag::code[]
1717
String userHome = System.getProperty("user.home");
18-
Path path = Paths.get(userHome, "arquivos");
18+
Path path = Paths.get(userHome, "files");
1919
System.out.println("Path: " + path);
2020

2121
try (WatchService service = FileSystems.getDefault().newWatchService();) {
2222
path.register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
2323

24-
System.out.println("Horário antes do poll sem timeout: " + LocalTime.now());
25-
WatchKey key1 = service.poll(); // retorna imediatamente, mesmo que não haja evento
26-
System.out.println("WatchKey do poll: " + key1);
27-
System.out.println("Horário depois do poll sem timeout: " + LocalTime.now());
24+
System.out.println("Time before poll without timeout: " + LocalTime.now());
25+
WatchKey key1 = service.poll(); // returns immediately even if there is no event
26+
System.out.println("WatchKey's poll: " + key1);
27+
System.out.println("Time after poll without timeout: " + LocalTime.now());
2828

29-
System.out.println("Horário antes do poll com timeout: " + LocalTime.now());
30-
WatchKey key2 = service.poll(5, TimeUnit.SECONDS); // retorna após 5 segundos, mesmo que não haja evento
31-
System.out.println("WatchKey do poll com timeout: " + key2);
32-
System.out.println("Horário depois do poll com timeout: " + LocalTime.now());
29+
System.out.println("Time before poll with timeout: " + LocalTime.now());
30+
WatchKey key2 = service.poll(5, TimeUnit.SECONDS); // returns after 5 seconds even if there is no event
31+
System.out.println("WatchKey's poll with timeout: " + key2);
32+
System.out.println("Time after poll with timeout: " + LocalTime.now());
3333
} catch (IOException | InterruptedException e) {
3434
e.printStackTrace();
3535
}

0 commit comments

Comments
 (0)