Skip to content

Commit f76ca26

Browse files
committed
feat(lang-enh): 🎸 try-with-resources, translated
Refers: #4
1 parent 89dc92d commit f76ca26

11 files changed

+100
-102
lines changed
Lines changed: 39 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,132 +1,130 @@
11
:java-package: src/org/j6toj8/languageenhancements
22
:section-java-package: ../../../{java-package}
33

4-
=== Try com recursos
4+
=== Try-with-resources
55

6-
.Objetivo
6+
.Objective
77
----
88
Develop code that uses try-with-resources statements, including using classes that implement the AutoCloseable interface.
9-
-
10-
Desenvolver código que utilize instruções try-with-resources, incluindo o uso de classes que implementam a interface AutoCloseable.
119
----
1210

13-
É esperado que o candidato saiba compreender e analisar o uso da instrução _try-with-resources_, incluindo classes que implementam a interface `AutoClosable`.
11+
The candidate is expected to understand and analyze the use of the _try-with-resources_ statement, including classes that implement the `AutoClosable` interface.
1412

15-
Antes de continuar, com base no exemplo a seguir, entenda a execução do método `main` e o que é apresentado no console após sua execução.
13+
Before proceeding, based on the following example, understand the execution of the `main` method and what is presented on the console after its execution.
1614

1715
[source,java,indent=0]
1816
.{java-package}/trywithresources/TryWithResouces_Complete.java
1917
----
2018
include::{section-java-package}/trywithresources/TryWithResouces_Complete.java[tag=code]
2119
----
2220

23-
O código acima utiliza dois arquivos, e faz leitura e escrita neles. A grande novidade desse código é a declaração de variáveis dentro de parênteses após a instrução `try`. Isso é a sintaxe chamada _try-with-resources_, e ela chama automaticamente o método `close()` dos recursos que estão sendo utilizados. Até o Java 6, seria necessário chamar o `close()` manualmente, como no exemplo abaixo.
21+
The previous code uses two files and reads and writes them. The big news of this code is the declaration of variables within parentheses after the `try` statement. This is the syntax called _try-with-resources_, and it automatically calls the `close ()` method of the resources being used. Until Java 6, you would need to call `close ()` manually, as in the following example.
2422

2523
[source,java,indent=0]
2624
.{java-package}/trywithresources/TryWithResouces_Java6.java
2725
----
2826
include::{section-java-package}/trywithresources/TryWithResouces_Java6.java[tag=code]
2927
----
3028

31-
. A instrução _try-with-resources_ fecha automaticamente os recursos que implementam a interface `AutoCloseable`.
29+
. The _try-with-resources_ statement automatically closes resources that implement the `AutoCloseable` interface.
3230

33-
. Ela não precisa de `catch` nem `finally` explícitos.
31+
. It does not need explicit `catch` or `finally`.
3432
+
3533
[source,java,indent=0]
3634
.{java-package}/trywithresources/TryWithResouces_AutoCloseable.java
3735
----
3836
include::{section-java-package}/trywithresources/TryWithResouces_AutoCloseable.java[tag=code]
3937
----
4038
+
41-
.Saída no console
39+
.console output
4240
[source,console]
4341
----
4442
try
45-
Porta fechada.
43+
Closed door.
4644
----
4745

48-
. A instrução _try-with-resources_ ainda pode ter `catch` e `finally`, apesar de não ser necessário. Nesse caso, os recursos são fechados depois do `try` e antes de qualquer `catch` ou `finally`.
46+
. The _try-with-resources_ statement can still have `catch` and `finally`, although it is not required. In this case, resources are closed after `try` and before either any `catch` or `finally`.
4947

50-
. O método `close` pode lançar uma exceção sendo capturada pelo `catch`, caso exista.
48+
. The `close` method may throw an exception being caught by `catch`, if any.
5149
+
5250
[source,java,indent=0]
5351
.{java-package}/trywithresources/TryWithResouces_WithCatchFinally.java
5452
----
5553
include::{section-java-package}/trywithresources/TryWithResouces_WithCatchFinally.java[tag=code]
5654
----
5755
+
58-
.Saída no console
56+
.console output
5957
[source,console]
6058
----
6159
try
62-
Porta fechada.
60+
Closed door.
6361
catch
6462
finally
6563
----
6664
+
67-
Ou seja, primeiro o `try` é chamado. Logo depois é chamado o método `close()` que ao final lança uma exceção. O `catch` captura essa exceção. E finalmente o `finally` é chamado.
65+
That is, first the `try` is called. Soon after is called the `close ()` method which at the end throws an exception. `Catch` catches this exception. And finally `finally` is called.
6866

69-
. Os recursos declarados na instrução _try-with-resources_ são fechados na ordem inversa da declaração.
67+
. Resources declared in the _try-with-resources_ statement are closed in the reverse order of the declaration.
7068
+
7169
[source,java,indent=0]
7270
.{java-package}/trywithresources/TryWithResouces_Order.java
7371
----
7472
include::{section-java-package}/trywithresources/TryWithResouces_Order.java[tag=code]
7573
----
7674
+
77-
.Saída no console
75+
.console output
7876
[source,console]
7977
----
80-
Olá.
81-
Gaveta fechada.
82-
Porta fechada.
78+
Hello.
79+
Drawer closed.
80+
Closed door.
8381
----
8482
+
85-
Ou seja, como a ordem de declaração dentro do _try-with-resources_ foi `Porta` e depois `Gaveta`, a ordem de chamada do método `close` é inversa: `Gaveta` e depois `Porta`.
83+
That is, since the declaration order within _try-with-resources_ was `Door` and then `Drawer`, the call order of the `close` method is reversed: `Drawer` and then `Door`.
8684

87-
. Os recursos declarados no _try-with-resources_ só estão disponível dentro do bloco `try`.
85+
. Resources declared in _try-with-resources_ are only available within the `try` block.
8886
+
8987
[source,java,indent=0]
9088
.{java-package}/trywithresources/TryWithResouces_ResourceInsideTry.java
9189
----
9290
include::{section-java-package}/trywithresources/TryWithResouces_ResourceInsideTry.java[tag=code]
9391
----
9492

95-
. Somente classes que implementam `AutoCloseable` podem ser utilizadas dentro do _try-with-resources_.
93+
. Only classes that implement `AutoCloseable` can be used within _try-with-resources_.
9694
+
9795
[source,java,indent=0]
9896
.{java-package}/trywithresources/TryWithResouces_NoAutoCloseable.java
9997
----
10098
include::{section-java-package}/trywithresources/TryWithResouces_NoAutoCloseable.java[tag=code]
10199
----
102100

103-
. Caso o método `close()` lance uma exceção checada (ou seja, que herda de `Exception`), o código só compila se existir um `catch` que capture aquela exceção, ou o método declare o `throws`.
101+
. If the `close ()` method throws a checked exception (i.e., inherits from `Exception`), the code only compiles if there is a `catch` that catches that exception or the method declares `throws`.
104102
+
105103
[source,java,indent=0]
106104
.{java-package}/trywithresources/TryWithResouces_CloseException.java
107105
----
108106
include::{section-java-package}/trywithresources/TryWithResouces_CloseException.java[tag=code]
109107
----
110108

111-
. O Java 5 já possuía uma interface chamada `Closeable`, porém ela permite lançar apenas `IOException`. A nova interface `AutoCloseable` permite lançar qualquer exceção. Como `Closeable` atende a implementação de `AutoCloseable`, ela agora estende `AutoCloseable`. Logo, todas as classes que já implementavam `Closeable` podem ser utilizadas dentro do _try-with-resources_. Veja abaixo como era a interface `Closeable` antes e a partir do Java 7:
109+
. Java 5 already had an interface called `Closeable`, but it allows only `IOException` to be thrown. The new `AutoCloseable` interface permits you to throw any exceptions. Since `Closeable` meets the implementation of `AutoCloseable`, it now extends `AutoCloseable`. So all classes that already implement `Closeable` can be used inside _try-with-resources_. Here's what the `Closeable` interface was like before and from Java 7:
112110
+
113-
.Antes do Java 7
111+
.Before Java 7
114112
[source,java]
115113
----
116114
public interface Closeable {
117115
public void close() throws IOException;
118116
}
119117
----
120118
+
121-
.A partir do Java 7
119+
.From Java 7
122120
[source,java]
123121
----
124122
public interface Closeable extends AutoCloseable {
125123
public void close() throws IOException;
126124
}
127125
----
128126

129-
. Um comportamento novo são as exceções suprimidas (suppressed). Se ambos o bloco `try` e o método `close` lançam exceção, a do `close` fica suprimida, pois a do `try` é lançada primeiro.
127+
. The new behavior is suppressed exceptions. If both the `try` block and the `close` method throw exception, that of `close` is suppressed because that of `try` is thrown first.
130128
+
131129
[source,java,indent=0]
132130
.{java-package}/trywithresources/TryWithResouces_Suppressed.java
@@ -139,38 +137,38 @@ include::{section-java-package}/trywithresources/TryWithResouces_Suppressed.java
139137
----
140138
try
141139
close
142-
erro no try
143-
erro no close
140+
error on try
141+
error on close
144142
----
145143
+
146-
Ou seja, a exceção que de fato foi capturada foi a do bloco `try`, pois foi lançada primeiro. A exceção lançada pelo método `close` ficou suprimida, e fica disponível em um array no método `getSuppressed()` da exceção.
144+
That is, the exception that was actually caught was the `try` block because it was thrown first. The exception thrown by the `close` method has been suppressed and is available in an array in the exception `getSuppressed()` method.
147145

148-
. E por fim, é necessário lembrar que a instrução `try` "comum" ainda precisa obrigatoriamente de um `catch` ou `finally`.
146+
. And lastly, it should be remembered that the _"default"_ `try` statement still necessarily needs a `catch` or `finally`.
149147
+
150148
[source,java,indent=0]
151149
.{java-package}/trywithresources/TryWithResouces_CommonTry.java
152150
----
153151
include::{section-java-package}/trywithresources/TryWithResouces_CommonTry.java[tag=code]
154152
----
155153

156-
==== Alguns tipos que implementam _Closeable_
154+
==== Some types that implement _Closeable_
157155

158-
* `InputStream` e suas subclasses (`FileInputStream`, `ObjectInputStream`, etc)
159-
* `OutputStream` e suas subclasses (`ByteArrayOutputStream`, `FileOutputStream`, etc)
160-
* `Reader` e suas subclasses (`BufferedReader`, `CharSequenceReader`)
161-
* `Writer` e suas subclasses (`BufferedWriter`, `PrintWriter`, etc)
156+
* `InputStream` and its subclasses (`FileInputStream`, `ObjectInputStream`, etc)
157+
* `OutputStream` and its subclasses (`ByteArrayOutputStream`, `FileOutputStream`, etc)
158+
* `Reader` and its subclasses (`BufferedReader`, `CharSequenceReader`)
159+
* `Writer` and its subclasses (`BufferedWriter`, `PrintWriter`, etc)
162160

163-
.Referências
161+
.References
164162
****
165163
166164
* Using Try-With-Resources
167165
+
168-
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 296). Wiley. Edição do Kindle.
166+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 296). Wiley. Kindle Edition.
169167
170168
* https://www.baeldung.com/java-try-with-resources[Java – Try with Resources.]
171169
172170
* https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html[The try-with-resources Statement.] Java Documentation.
173171
174-
* https://pt.stackoverflow.com/questions/172909/como-funciona-o-try-with-resources/172910#172910[Como funciona o try-with-resources?]
172+
* https://pt.stackoverflow.com/questions/172909/como-funciona-o-try-with-resources/172910#172910[Como funciona o try-with-resources?] (pt-BR)
175173
176174
****

src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_AutoCloseable.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
public class TryWithResouces_AutoCloseable {
66

77
// tag::code[]
8-
static class Porta implements AutoCloseable {
8+
static class Door implements AutoCloseable {
99
@Override
1010
public void close() { // chamado automaticamente pelo try-with-resources
11-
System.out.println("Porta fechada.");
11+
System.out.println("Closed door.");
1212
}
1313
}
1414

1515
public static void main(String[] args) throws FileNotFoundException {
16-
try (Porta porta = new Porta()) { // Porta instanciada dentro da instrução try-with-resources
16+
try (Door door = new Door()) { // Door instantiated within the try-with-resources statement
1717
System.out.println("try");
1818
}
1919
}

src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CloseException.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,29 @@
33
public class TryWithResouces_CloseException {
44

55
// tag::code[]
6-
static class Porta implements AutoCloseable {
6+
static class Door implements AutoCloseable {
77
@Override
8-
public void close() throws Exception { // declara throws Exception obrigatoriamente
8+
public void close() throws Exception { // must declare throws Exception
99
throw new Exception();
1010
}
1111
}
1212

1313
void try1() {
14-
try (Porta porta = new Porta()) { // NÃO COMPILA - exceção do close() não é capturada nem declarada
15-
System.out.println("Olá 1");
14+
try (Door door = new Door()) { // NOT COMPILING - the exception of close() is not captured or declared
15+
System.out.println("Hello 1");
1616
}
1717
}
1818

1919
void try2() {
20-
try (Porta porta = new Porta()) {
21-
System.out.println("Olá 2");
22-
} catch (Exception e) { // COMPILA - exceção capturada
20+
try (Door door = new Door()) {
21+
System.out.println("Hello 2");
22+
} catch (Exception e) { // COMPILES - exception caught
2323
}
2424
}
2525

26-
void try3() throws Exception { // COMPILA - exceção declarada no método
27-
try (Porta porta = new Porta()) {
28-
System.out.println("Olá 3");
26+
void try3() throws Exception { // COMPILES - exception declared in the method
27+
try (Door door = new Door()) {
28+
System.out.println("Hello 3");
2929
}
3030
}
3131
// end::code[]

src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_CommonTry.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,23 @@ public class TryWithResouces_CommonTry {
66
public static void main(String[] args) {
77
try {
88
System.out.println("try");
9-
} // NÃO COMPILA - try "comum" sem catch ou finally
9+
} // NOT COMPILING - "common" try without catch or finally
1010

1111
try {
1212
System.out.println("try");
1313
} catch (Exception e) {
14-
} // COMPILA - try "comum" só com catch
14+
} // COMPILES - "common" try with catch only
1515

1616
try {
1717
System.out.println("try");
1818
} finally {
19-
} // COMPILA - try "comum" só com finally
19+
} // COMPILES - "common" try with finally only
2020

2121
try {
2222
System.out.println("try");
2323
} catch (Exception e) {
2424
} finally {
25-
} // COMPILA - try "comum" com catch e finally
25+
} // COMPILES - "common" try with catch and finally
2626
}
2727
// end::code[]
2828
}

src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Complete.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,35 +11,35 @@ public class TryWithResouces_Complete {
1111

1212
// tag::code[]
1313
public static void main(String[] args) throws IOException {
14-
// criação de 2 arquivos
15-
File file = new File("arquivo.txt");
16-
File file2 = new File("arquivo2.txt");
14+
// creates 2 files
15+
File file = new File("file.txt");
16+
File file2 = new File("file2.txt");
1717

18-
// Exemplo try-with-resources com PrintWriter
18+
// try-with-resources example with PrintWriter
1919
try (PrintWriter writer = new PrintWriter(file)) {
20-
// escreve no arquivo.txt
21-
writer.println("Olá Mundo!");
20+
// write to file.txt
21+
writer.println("Hello World!");
2222
}
2323

24-
// Exemplo try-with-resources com BufferedReader
24+
// try-with-resources example with BufferedReader
2525
try (BufferedReader reader = Files.newBufferedReader(file.toPath())) {
26-
// imprime no console uma linha do arquivo.txt
26+
// print a line from file.txt to the console
2727
System.out.println(reader.readLine());
2828
}
2929

30-
// Exemplo try-with-resources com BufferedReader e BufferedWriter
30+
// try-with-resources example with BufferedReader and BufferedWriter
3131
try (BufferedReader reader = Files.newBufferedReader(file.toPath());
3232
BufferedWriter writer = Files.newBufferedWriter(file2.toPath())) {
33-
// lê a linha do arquivo.txt e escreve no arquivo2.txt
33+
// read line from file.txt and write to file2.txt
3434
writer.write(reader.readLine() + "2");
3535
}
3636

37-
// Exemplo try-with-resources com BufferedReader
37+
// try-with-resources example with BufferedReader
3838
try (BufferedReader reader = Files.newBufferedReader(file2.toPath())) {
39-
// imprime no console uma linha do arquivo2.txt
39+
// print a line from file2.txt to the console
4040
System.out.println(reader.readLine());
4141
}
42-
// todos os Reader e Writer já foram fechados.
42+
// all Reader and Writer have already been closed
4343
}
4444
// end::code[]
4545
}

src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_Java6.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@ public class TryWithResouces_Java6 {
88

99
// tag::code[]
1010
public static void main(String[] args) throws FileNotFoundException {
11-
File file = new File("arquivo.txt");
11+
File file = new File("file.txt");
1212
PrintWriter writer = null;
1313
try {
1414
writer = new PrintWriter(file);
15-
writer.println("Olá Mundo!");
15+
writer.println("Hello World!");
1616
} finally {
1717
if (writer != null) {
18-
writer.close(); // fechando o writer manualmente
18+
writer.close(); // closing the writer manually
1919
}
2020
}
2121
}

src/org/j6toj8/languageenhancements/trywithresources/TryWithResouces_NoAutoCloseable.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
public class TryWithResouces_NoAutoCloseable {
44

55
// tag::code[]
6-
static class Prateleira {}
6+
static class Shelf {}
77

88
public static void main(String[] args) {
9-
try (Prateleira prateleira = new Prateleira()) { // NÃO COMPILA - Prateleira não implementa AutoClosable
10-
System.out.println("Olá");
9+
try (Shelf shelf = new Shelf()) { // NOT COMPILING - Shelf do not implement AutoCloseable
10+
System.out.println("Hello");
1111
}
1212
}
1313
// end::code[]

0 commit comments

Comments
 (0)