OnJava8-Examples/files/AddAndSubtractPaths.java

82 lines
2.3 KiB
Java
Raw Permalink Normal View History

2015-12-02 09:20:27 -08:00
// files/AddAndSubtractPaths.java
// (c)2021 MindView LLC: see Copyright.txt
2015-12-02 09:20:27 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-12-02 09:20:27 -08:00
import java.nio.file.*;
2015-12-06 11:45:16 -08:00
import java.io.IOException;
2015-12-02 09:20:27 -08:00
public class AddAndSubtractPaths {
static Path base = Paths.get("..", "..", "..")
.toAbsolutePath()
.normalize();
static void show(int id, Path result) {
if(result.isAbsolute())
System.out.println("(" + id + ")r " +
base.relativize(result));
else
System.out.println("(" + id + ") " + result);
2015-12-06 11:45:16 -08:00
try {
2016-01-25 18:05:55 -08:00
System.out.println("RealPath: "
+ result.toRealPath());
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
2015-12-06 11:45:16 -08:00
System.out.println(e);
}
2015-12-02 09:20:27 -08:00
}
public static void main(String[] args) {
System.out.println(System.getProperty("os.name"));
System.out.println(base);
Path p = Paths.get("AddAndSubtractPaths.java")
.toAbsolutePath();
show(1, p);
Path convoluted = p.getParent().getParent()
.resolve("strings")
.resolve("..")
.resolve(p.getParent().getFileName());
show(2, convoluted);
show(3, convoluted.normalize());
Path p2 = Paths.get("..", "..");
show(4, p2);
show(5, p2.normalize());
show(6, p2.toAbsolutePath().normalize());
Path p3 = Paths.get(".").toAbsolutePath();
Path p4 = p3.resolve(p2);
show(7, p4);
show(8, p4.normalize());
Path p5 = Paths.get("").toAbsolutePath();
show(9, p5);
show(10, p5.resolveSibling("strings"));
2015-12-06 11:45:16 -08:00
show(11, Paths.get("nonexistent"));
2015-12-02 09:20:27 -08:00
}
}
/* Output:
Windows 10
C:\Git
(1)r OnJava8\ExtractedExamples\files\AddAndSubtractPaths.java
RealPath:
C:\Git\OnJava8\ExtractedExamples\files\AddAndSubtractPaths.java
(2)r OnJava8\ExtractedExamples\files
RealPath: C:\Git\OnJava8\ExtractedExamples\files
(3)r OnJava8\ExtractedExamples\files
RealPath: C:\Git\OnJava8\ExtractedExamples\files
2015-12-02 09:20:27 -08:00
(4) ..\..
RealPath: C:\Git\OnJava8
2015-12-02 09:20:27 -08:00
(5) ..\..
RealPath: C:\Git\OnJava8
(6)r OnJava8
RealPath: C:\Git\OnJava8
(7)r OnJava8
RealPath: C:\Git\OnJava8
(8)r OnJava8
RealPath: C:\Git\OnJava8
(9)r OnJava8\ExtractedExamples\files
RealPath: C:\Git\OnJava8\ExtractedExamples\files
(10)r OnJava8\ExtractedExamples\strings
RealPath: C:\Git\OnJava8\ExtractedExamples\strings
2015-12-06 11:45:16 -08:00
(11) nonexistent
java.nio.file.NoSuchFileException:
C:\Git\OnJava8\ExtractedExamples\files\nonexistent
2015-12-02 09:20:27 -08:00
*/