OnJava8-Examples/files/PathInfo.java

102 lines
2.4 KiB
Java
Raw Normal View History

2015-12-02 09:20:27 -08:00
// files/PathInfo.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.*;
import java.net.URI;
import java.io.File;
import java.io.IOException;
public class PathInfo {
static void show(String id, Object p) {
System.out.println(id + p);
2015-12-02 09:20:27 -08:00
}
static void info(Path p) {
show("toString:\n ", p);
show("Exists: ", Files.exists(p));
show("RegularFile: ", Files.isRegularFile(p));
show("Directory: ", Files.isDirectory(p));
show("Absolute: ", p.isAbsolute());
show("FileName: ", p.getFileName());
show("Parent: ", p.getParent());
show("Root: ", p.getRoot());
System.out.println("******************");
2015-12-02 09:20:27 -08:00
}
public static void main(String[] args) {
System.out.println(System.getProperty("os.name"));
info(Paths.get(
"C:", "path", "to", "nowhere", "NoFile.txt"));
Path p = Paths.get("PathInfo.java");
info(p);
Path ap = p.toAbsolutePath();
info(ap);
info(ap.getParent());
try {
info(p.toRealPath());
2017-01-22 16:48:11 -08:00
} catch(IOException e) {
2015-12-02 09:20:27 -08:00
System.out.println(e);
}
URI u = p.toUri();
System.out.println("URI:\n" + u);
2015-12-02 09:20:27 -08:00
Path puri = Paths.get(u);
System.out.println(Files.exists(puri));
File f = ap.toFile(); // Don't be fooled
}
}
/* Output:
Windows 10
toString:
C:\path\to\nowhere\NoFile.txt
2015-12-02 09:20:27 -08:00
Exists: false
RegularFile: false
Directory: false
Absolute: true
FileName: NoFile.txt
Parent: C:\path\to\nowhere
Root: C:\
******************
toString:
PathInfo.java
2015-12-02 09:20:27 -08:00
Exists: true
RegularFile: true
Directory: false
Absolute: false
FileName: PathInfo.java
Parent: null
Root: null
******************
toString:
C:\Git\OnJava8\ExtractedExamples\files\PathInfo.java
2015-12-02 09:20:27 -08:00
Exists: true
RegularFile: true
Directory: false
Absolute: true
FileName: PathInfo.java
Parent: C:\Git\OnJava8\ExtractedExamples\files
2015-12-02 09:20:27 -08:00
Root: C:\
******************
toString:
C:\Git\OnJava8\ExtractedExamples\files
2015-12-02 09:20:27 -08:00
Exists: true
RegularFile: false
Directory: true
Absolute: true
FileName: files
Parent: C:\Git\OnJava8\ExtractedExamples
2015-12-02 09:20:27 -08:00
Root: C:\
******************
toString:
C:\Git\OnJava8\ExtractedExamples\files\PathInfo.java
2015-12-02 09:20:27 -08:00
Exists: true
RegularFile: true
Directory: false
Absolute: true
FileName: PathInfo.java
Parent: C:\Git\OnJava8\ExtractedExamples\files
2015-12-02 09:20:27 -08:00
Root: C:\
******************
URI:
file:///C:/Git/OnJava8/ExtractedExamples/files/PathInfo.java
2015-12-02 09:20:27 -08:00
true
*/