Skip to content

Commit

Permalink
feat(file-io): 🎸 paths, translated
Browse files Browse the repository at this point in the history
Refers: #9
  • Loading branch information
rcmoutinho committed Sep 12, 2019
1 parent 8d4c0a2 commit 3ef7e75
Show file tree
Hide file tree
Showing 12 changed files with 137 additions and 138 deletions.
151 changes: 75 additions & 76 deletions book/07-file-io/sections/01-paths.asc
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,28 @@

=== Paths

.Objetivo
.Objective
--------------------------------------------------
Operate on file and directory paths by using the Paths class
-
Operar em arquivos e diretórios usando a classe Paths
--------------------------------------------------

As classes `Path` e `Paths` são novidades do Java 7.
The `Path` and `Paths` classes are new to Java 7.

A classe `Path` representa um arquivo ou um diretório no sistema de arquivos, e a maioria das suas operações não altera diretamente arquivos ou diretórios.
The `Path` class represents a file or directory in the file system, and most of its operations do not directly change files or directories.

A classe `Paths` contém métodos estáticos para a criação de `Path`.
The `Paths` class contains static methods for creating `Path`.

Para que os exemplos executem independente do sistema, será utilizado o diretório do usuário, que no Java está disponível em uma propriedade da JVM chamada `user.home`.
For the examples to run system-independent, the user directory will be used, which in Java is available in a JVM property called `user.home`.

. Existem inúmeras formas de obter uma instância de `Path`.
. There are numerous ways to get an instance of `Path`.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Creation.java
----
include::{section-java-package}/paths/Paths_Creation.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Expand All @@ -42,189 +40,189 @@ Path 9: /home/rinaldo/arquivo.txt
Path 10: /home/rinaldo
----

. É possível criar uma instância de `Path` apontando para um diretório ou arquivo que não existe.
. You can create an instance of `Path` by pointing to a directory or file that does not exist.
+
[source,java,indent=0]
.{java-package}/paths/Paths_CreationDoesntExists.java
----
include::{section-java-package}/paths/Paths_CreationDoesntExists.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Path: /home/rinaldo/arquivoQueNaoExiste.txt
Path: /home/rinaldo/fileThatDoesNotExist.txt
----

. É possível converter um `Path` para um `File`.
. It is possible to convert a `Path` to a `File`.
+
[source,java,indent=0]
.{java-package}/paths/Paths_ToFile.java
----
include::{section-java-package}/paths/Paths_ToFile.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Path: /home/rinaldo/arquivoQueNaoExiste.txt
File: /home/rinaldo/arquivoQueNaoExiste.txt
Path: /home/rinaldo/fileThatDoesNotExist.txt
File: /home/rinaldo/fileThatDoesNotExist.txt
----

. Existem inúmeros método no `Path` para recuperar informações a seu respeito.
. There are numerous methods in `Path` to retrieve information about it.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Information.java
----
include::{section-java-package}/paths/Paths_Information.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Representação em String: /home/rinaldo/arquivos/arquivo.txt
Nome do Arquivo: arquivo.txt
Diretório Superior: /home/rinaldo/arquivos
Diretório Raiz: /
É absoluto? true
String representation: /home/rinaldo/files/file.txt
File Name: file.txt
Top Directory: /home/rinaldo/files
Root Directory: /
Is it absolute?: true
Representação em String: home/rinaldo/arquivos
Nome do Arquivo: arquivos
Diretório Superior: home/rinaldo
Diretório Raiz: null
É absoluto? false
String representation: home/rinaldo/files
File Name: files
Top Directory: home/rinaldo
Root Directory: null
Is it absolute?: false
----

. É possível recuperar os elementos do `Path` individualmente.
. It is possible to retrieve the elements of `Path` individually.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Names.java
----
include::{section-java-package}/paths/Paths_Names.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
home
rinaldo
arquivos
arquivo.txt
files
file.txt
----

. É possível converter um `Path` relativo para um absoluto.
. It is possible to convert a relative `Path` to an absolute.
+
[source,java,indent=0]
.{java-package}/paths/Paths_ToAbsolute.java
----
include::{section-java-package}/paths/Paths_ToAbsolute.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
arquivos
É absoluto? false
files
Is it absolute? false
/home/rinaldo/Desenvolvimento/git/java6-to-java8/arquivos
É absoluto? true
/home/rinaldo/Desenvolvimento/git/java6-to-java8/files
Is it absolute? true
----
+
Neste caso a saída do console vai depende do diretório onde a aplicação está sendo executada.
In this case the console output will depend on the directory where the application is running.

. É possível criar _Sub-Paths_ a partir de um `Path`.
. You can create _Sub-Paths_ from a `Path`.
+
[source,java,indent=0]
.{java-package}/paths/Paths_SubPath.java
----
include::{section-java-package}/paths/Paths_SubPath.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Path: /home/rinaldo/arquivos/arquivo1.txt
Path: /home/rinaldo/arquivos/file1.txt
home
home/rinaldo
rinaldo/arquivos
arquivos/arquivo1.txt
rinaldo/files
arquivos/file1.txt
Exception in thread "main" java.lang.IllegalArgumentException
at sun.nio.fs.UnixPath.subpath(UnixPath.java:348)
at sun.nio.fs.UnixPath.subpath(UnixPath.java:43)
at org.j6toj8.fileio.paths.Paths_SubPath.main(Paths_SubPath.java:28)
----

. É possível remover redundâncias de um `Path` com o método `normalize`.
. You can remove redundancies from a `Path` with the `normalize` method.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Normalize.java
----
include::{section-java-package}/paths/Paths_Normalize.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Path: /home/rinaldo/arquivos/./arquivo1.txt
Path normalize: /home/rinaldo/arquivos/arquivo1.txt
Path: /home/rinaldo/files/./file1.txt
Path normalize: /home/rinaldo/files/file1.txt
Path: /home/rinaldo/arquivos/../arquivo1.txt
Path normalize: /home/rinaldo/arquivo1.txt
Path: /home/rinaldo/files/../file1.txt
Path normalize: /home/rinaldo/file1.txt
----

. É possível unir duas instâncias de `Path` com o método `resolve`.
. You can join two instances of `Path` with the `resolve` method.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Resolve.java
----
include::{section-java-package}/paths/Paths_Resolve.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Absoluto + Relativo: /home/rinaldo/arquivos/arquivo1.txt
Relativo + Absoluto: /home/rinaldo/arquivos
Absoluto + Absoluto: /home/rinaldo/arquivos
Relativo + Relativo: arquivo1.txt/arquivo1.txt
Absolute + Relative: /home/rinaldo/files/file1.txt
Relative + Absolute: /home/rinaldo/files
Absolute + Absolute: /home/rinaldo/files
Relative + Relative: file1.txt/file1.txt
----
+
Perceba que sempre que o argumento é um `Path` absoluto, o resultado final é ele mesmo.
Note that whenever the argument is an absolute `Path`, the end result is itself.
+
Quando o argumento é um `Path` relativo, ele é acrescentado ao original, seja este absoluto ou relativo.
When the argument is a relative `Path`, it is appended to the original, either absolute or relative.

. É possível derivar um `Path` de outro com o método `relativize`.
. It is possible to derive one `Path` from another with the `relativize` method.
+
[source,java,indent=0]
.{java-package}/paths/Paths_Relativize.java
----
include::{section-java-package}/paths/Paths_Relativize.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
Absoluto 1: /home/rinaldo/arquivos
Absoluto 2: /home/rinaldo/arquivos/arquivo1.txt
Relativo 1: arquivo1.txt
Relativo 2: arquivos/arquivo1.txt
Absoluto 1 + Absoluto 2: arquivo1.txt
Absoluto 2 + Absoluto 1: ..
Relativo 1 + Relativo 2: ../arquivos/arquivo1.txt
Relativo 2 + Relativo 1: ../../arquivo1.txt
Absolute 1: /home/rinaldo/files
Absolute 2: /home/rinaldo/files/file1.txt
Relative 1: file1.txt
Relative 2: files/file1.txt
Absolute 1 + Absolute 2: file1.txt
Absolute 2 + Absolute 1: ..
Relative 1 + Relative 2: ../files/file1.txt
Relative 2 + Relative 1: ../../file1.txt
java.lang.IllegalArgumentException: 'other' is different type of Path
at sun.nio.fs.UnixPath.relativize(UnixPath.java:416)
at sun.nio.fs.UnixPath.relativize(UnixPath.java:43)
Expand All @@ -235,41 +233,42 @@ java.lang.IllegalArgumentException: 'other' is different type of Path
at org.j6toj8.fileio.paths.Paths_Relativize.main(Paths_Relativize.java:40)
----
+
Todas essas combinações podem aparecere no exame, então entenda bem como cada uma delas se comporta. Lembre-se principalmente de que não é possível derivar um `Path` absoluto de um relativo, e vice-versa.
All of these combinations may appear on the exam, so understand well how each one behaves. Remember especially that it is not possible to derive an absolute `Path` from a relative, and vice versa.

. É possível converter um `Path` sintético, que não aponta de fato para um arquivo no sistema de arquivos, em um `Path` real, que aponta para um arquivo ou diretório que existe no sistema de arquivos.
. It is possible to convert a synthetic `Path`, which does not actually point to a file in the file system, into a real `Path`, which points to a file or directory that exists in the file system.
+
[source,java,indent=0]
.{java-package}/paths/Paths_ToRealPath.java
----
include::{section-java-package}/paths/Paths_ToRealPath.java[tag=code]
----
+
.Saída no console
.console output
[source,console]
----
User home: /home/rinaldo
realPath: /home/rinaldo/arquivo1.txt
java.nio.file.NoSuchFileException: /home/rinaldo/arquivoQueNaoExiste.txt
realPath: /home/rinaldo/file1.txt
java.nio.file.NoSuchFileException: /home/rinaldo/fileThatDoesNotExist.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixPath.toRealPath(UnixPath.java:837)
at org.j6toj8.fileio.paths.Paths_ToRealPath.main(Paths_ToRealPath.java:25)
----
+
Perceba que é lançada exceção caso o arquivo realmente não exista no sistema de arquivos.
Note that an exception is thrown if the file does not actually exist in the file system.

.References
****
* Introducing NIO.2
+
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 454). Wiley. Edição do Kindle.
Boyarsky, Jeanne; Selikoff, Scott. OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide (p. 454). Wiley. Kindle Edition.
* https://www.baeldung.com/java-nio-2-path[Java NIO2 Path API.]
* https://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html[Class Paths.] Java Plataform SE 7.
* https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html[Path Operations.] The Java™ Tutorials.
****
****
24 changes: 12 additions & 12 deletions src/org/j6toj8/fileio/paths/Paths_Creation.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,47 +9,47 @@ public class Paths_Creation {

public static void main(String[] args) {
// tag::code[]
// diretório padrão do usuário
// default user directory
String userHome = System.getProperty("user.home");
System.out.println("User home: " + userHome);

// path absoluto
// absolute path
Path path1 = Paths.get("/home/rinaldo");
System.out.println("Path 1: " + path1);

// path absoluto dividido em strings
// absolute path divided into strings
Path path2 = Paths.get("/", "home", "rinaldo");
System.out.println("Path 2: " + path2);

// path absoluto a partir do userHome
// absolute path from userHome
Path path3 = Paths.get(userHome);
System.out.println("Path 3: " + path3);

// path absoluto para um arquivo
// absolute path to a file
Path path4 = Paths.get("/home/rinaldo/arquivos/arquivo.txt");
System.out.println("Path 4: " + path4);

// path absoluto para um arquivo a partir do userHome
// absolute path to a file from userHome
Path path5 = Paths.get(userHome, "arquivos", "arquivo.txt");
System.out.println("Path 5: " + path5);

// path absoluto em um sistema windows
// absolute path on a windows system
Path path6 = Paths.get("C:/users/rinaldo");
System.out.println("Path 6: " + path6);

// path absoluto windows divido em strings
// absolute path on a windows split into strings
Path path7 = Paths.get("C:", "users", "rinaldo");
System.out.println("Path 7: " + path7);

// path relativo
// relative path
Path path8 = Paths.get("rinaldo");
System.out.println("Path 8: " + path8);

// path a partir de uma URI
// path from a URI
Path path9 = Paths.get(URI.create("file:///home/rinaldo/arquivos/arquivo.txt"));
System.out.println("Path 9: " + path9);
// path sem utilizar a classe Paths - produz o mesmo resultado

// path without using the Paths class - produces the same result
Path path10 = FileSystems.getDefault().getPath("/home/rinaldo");
System.out.println("Path 10: " + path10);
// end::code[]
Expand Down
Loading

0 comments on commit 3ef7e75

Please sign in to comment.