Chapter 9: NIO Flashcards

1
Q

Path interface/Paths class

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Absolute vs. Relative Path

A

If it starts with / or a drive letter e.g. C:\ then it is absolute, otherwise it is relative.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Paths methods

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

FileSystem object

A

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("")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Converting between File and Path

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Common optional arguments

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Viewing a Path

A

.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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Access Path componenets

A

.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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Check Path type

A

.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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Subpath

A

.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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Path symbols

A

. = 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Files class methods

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

BufferedReader + BufferedWriter

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

File attributes

A

.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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Views

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Attributes and View classes

A

BasicFileAttributes and BasicFileAttributeView.

Files.readAttributes(Path, Class<a>) eg. BasicFileAttributes.class.</a>

contains standard file attributes
+ isOther() checks if not file/directory/symbolic link.
+ lastAccessTime()
+ creationTime()
+ fileKey() unique identifier for file within the system of null if not supported

Files.getAttributeView(Path, Class</a><a>) e.g. BasicFileAttributeView.class
Used to change values, but you can only really change Time Values </a> -> Note if you pass null to time values it won't update
17
Q

Streams in NIO.2

A

Search strategy for traversing file directories. Streams API uses depth-first. i.e. goes straight to an arbitrary leaf then as it comes back up it goes through each path it skipped along the way. Has a maximum value away from root node, which is Integer.MAX_VALUE.
Files.walk(path): returns a Stream which traverses the directory depth-first in a a lazy manner (i.e. doesn’t load entire graph, just adds when it comes across elements)
.filter(..): filters files based on a condition (This can throw IOException. Note: won’t traverse symbolic links by default, but can pass in FOLLOW_LINKS to make sure it does. Can throw FileSystemLoopException if it gets into a loop though!
Files.find(Path, int depth parameter for depth strategy search, BiPredicate)

Files.list( searches 1 level deep and is anallogous to Files.listFiles()
Files.lines() returns a Stream
lines evaluated lazily so entire contents aren’t loaded into memory, so you can avoid OutOfMemeoryError!

18
Q

Path resolve

A

From an existing path object, if you resolve a String, it will return a new Path with the passed in String path

19
Q

Files.find

A

(Path start, int depth, BiPredicate matcher, ooptions…)