Chapter 9: NIO Flashcards
Path interface/Paths class
Path is an interface and Paths class has factory methods for obtaining a Path object. The Path object will handle system-specific details for the current platform. Files contains helper methods to operate on instance of Path objects.
Absolute vs. Relative Path
If it starts with / or a drive letter e.g. C:\ then it is absolute, otherwise it is relative.
Paths methods
Paths.get(“”)
Paths.get(“”, “”, “”) Can provide an array of Strings and JVM will handle insertion of slashes.
Paths.get(URI).
Paths.get(new URI(“file://”))
Can use for local or network paths e.g. http:// of ftp://
Paths.toURI method converts a path instance back to a URI instance.
FileSystem object
Filesystem has a protected constructor. So you can access via FileSystems factory class.
Allows you to get access to a Path.
e.g. Path p = FileSystems.getDefault().getPath("") or to an external FileSytem Path p = FileSystems.getFileSystem(new URI("")).getPath("")
Converting between File and Path
Path p = File.toPath()
File f = Path.toFile()
Recommended to use Path instead of File as more feature rich and built in support for file systems
Common optional arguments
ENUM values
NOFOLLOW_LINKS: Symbolic links are not traversed when encountered (Symbolic link is a file containing links or references to another file or directory)
FOLLOW_LINKS: Symbolic links followed
COPY_ATTRIBUTES: All metadata about a file is copied
REPLACE_EXISTING: If target file exists already it will replace it, but will throw Exception if existing is not found
ATOMIC_MOVE: Any process using the file sees a complete record. A system not supporting this will throw an AtomicMoveNotSupportedException.
Viewing a Path
.toString() = String representation of the entire Path
.getNameCount() /.getName(int) gets number of elements in Path and the element as int.
Returns componenets of a Path object as a new Path object. Zero-indexed. File system root is excluded from path components.
Access Path componenets
.getFileName()
returns furthest element from the Root as sa Path object
.getParent()
returns Parent path or null if no Parent
Note: if Path is relative will stay inside working directory and won’t go to rest of file system
.getRoot() gets root element of null if Path is relative.
Check Path type
.isAbsolute() returns false if relative path
.toAbsolutePath() converts a relative Path to absolute Path (If it already is an absolute path it will return the same thing i.e. a new Path object with the same value)
Subpath
.subPath(int start, int end)
Returns a Path object
Throws Exception at Runtime if out of bounds or if start and end are the same
Path symbols
. = reference to current directory
.. = returns to parent of current directory
.relativize() method returns a relative Path from one object to another.
e.g. .._\ goes up one directory level then go down 2 to the file you want. Both files must be either Absolute or relative otherwise throws illegalArgumentException
If on Windows both Absolutely paths must have the same root directory or drive letter.
.resolve() joins an existing path to the current path.
Note: relativize and resolve don’t clean up path symbols.
If two absolute paths are provided, then the first path is ignored.
.normalize() will remove Path symbols (Note doesn’t check if File actually exists).
.toRealPath() implicitly calls .normalize(), so reumoves redundant path elements. Supports NOFOLLOW_LINKS (is only method which does). Throws checked IOException (if File or directory does not exist). Will evaluate symbolic links between paths if NOFOLLOW_LINKS is not passed in.
Files class methods
Files class is a nio.2 helper class for dealing with Files. Most methods throw Exception if file doesn't exist. Most method names are more straightforward. e.g. .move() instead of .renameTo() Methods: .exists() checks if Path exists .isSameFile(). Checks if 2 Paths point to same File.Directory (e.g. by following symbolic links). Doesn't check contents of file. Throws IOException is either file not found. .createDirectory() or .createDirectories(). Plural form will create target directory as well as nonexistent parent directories leading up to parent directory. Can throw IOException if directory cannot be created or it already exists. e.g. in singular form if parent directories don't exist it will throw Exception .copy(Path p1, Path p2) Copies from one file.directory to another. Only does a shallow copy, so won't copy over subdirectories etc. If you copy a directory to a new directory, it will just create a directory without the contents. also .copy(InputStream, Path) supports varargs since it's writing to a Path .copy(Path, OutputStream) Doesn't support varargs .move(Path p1, Path p2). Moves/renames a file or directory. Throws IOException if directories not found or could not be moved. By default will follow links, but can use varargs to avoid this. .delete() If directory not empty throws Directory NotEmptyException. If target is a symbolic link, it will be deleted, not the actual file. So can remove symbolic links this way. .deleteIfExists() doesn't throw Exception
BufferedReader + BufferedWriter
Files.newBufferedReader(Path, Charset) Files.newBufferedWriter(Path, Charset) -->Overwrites file if exists already Files.readAllLines(). Returns ordered list of strings. Can also pass a Charset. NoteL loads entire file, so you may experience OutOfMemory error.
File attributes
.isDirectory()
.isRegularFile()
.isSymbolicLink() –> Returns true if symbolic link points to a real file.
Each of the above doesn’t throw an Exception if file doesn’t exist.
.isHidden() –> Checks if file starts with . in linux this means file is hidden. Throws IOException if file isn’t there.
isReadable() + isExecutable() doesn’t throw exception if file doesn’t exist (returns false instead)
.size() size of file in bytes (throws IOException)
.getLastModifiedTime() returns a FileTime object. container with date/time info and has a .toMillis() method to get the epoch time.
.setLastModifiedTime()
.getOwner() returns UserPrincipal, which represents the owner
.setOwner() Takes Path and UserPrincipal
Can use UserPrincipalLookupService helper class to find the user.
This can be obtained via FileSystems.geDefault() or .getFileSystem() on Path object, then can call .lookupPrincipalByName.
Views
A view is a group of relateed attributes for a particular file system and helps to reduce the number of round trips between Java and the OS.