NIO.2 Flashcards
Path object
Represents a hierarchical path on the storage system to a file or directory. In this manner, Path is a direct replacement for the legacy java.io.File class, and conceptually it contains many of the same properties.
Contains support for symbolic links
3 ways to create a Path object using the Paths class
1) Path path1 = Paths.get(file)
2) You could also use the multiple argument version which will insert the proper separation character between each string argument
Path path2 = Paths.get(“mydir1”, “mydir2”, “myfile”) //Same as “mydir1/mydir2/myfile” in linux based
3) You could also use a URI:
Path path3 = Paths.get(new URI(“file:///home/mydir”));
Note that the path used in the URI must be an absolute path.
Should you use forward slashes (/) or backward slashes () when separating file names in paths?
The JVM can convert either to the correct version for the current operating system, so you can use either of them.
Note: If you use the \ as the first character in a Linux based file system, it won’t be considered an absolute path still.
Also could throw a URISyntaxException
How to convert a Path object path to a URI
path.toURI()
How to create a Path object using the FileSystems class
Path path =FileSystems.getDefault().getPath(string);
How to access a remote filesystem
FileSystem fs = FileSystems.getFileSystem(uri);
Optional argument
NOFOLLOW_LINKS
If provided, symbolic links when encountered will not be traversed. Useful for performing operations on symbolic links themselves rather than their target.
Optional argument
FOLLOW_LINKS
If provided, symbolic links when encountered will be traversed.
Optional argument
COPY_ATTRIBUTES
If provided, all metadata about a file will be copied with it.
Optional argument
REPLACE_EXISTING
If provided and the target file exists, it will be replaced; otherwise, if it is not provided, an exception will be thrown if the file already exists.
Optional argument
ATOMIC_MOVE
The operation is performed in an atomic manner within the file system, ensuring that any process using the file sees only a complete record. Method using it may throw an exception if the feature is unsupported by the file system.
Path methods
getNameCount()
getName(int)
- Returns number of elements in the path
- Returns the name of the element at the specified position
Note: The root element / is not counted
Path methods
getFileName()
getParent()
getRoot()
- Returns a Path instance representing the filename, which is the farthest element from the root.
- Returns a Path instance representing the parent path or null if there is no such parent. It will only go as far up the path as is explicitly specified in the path definition.
- Returns the root element for the Path object or null if the Path object is relative.
Path methods
isAbsolute()
toAbsolutePath()
- Returns true if the path the object references is absolute and false if the path the object references is relative.
- Converts a relative Path object to an absolute Path by joining it to the current working directory.
Path method
subpath(int a, int b)
Returns a relative subpath of the Path object, referenced by an inclusive start index and an exclusive end index.
Path method
path1.relativize(path2)
returns the Path from path1 to path2
both must be relative or both must be absolute, and an IllegalArgumentException will be thrown if absolute and relative paths are mixed
Note: these do not necessarily have to be actual files in the filesystem, since it just looks at the two Paths it gives you
Path method
path1.resolve(path2)
If path2 is relative, then the result is path2 appended to path1
If path2 is absolute, then path2 is returned
Path method
normalize()
Returns a path that is this path with redundant name elements eliminated.
Path method
toRealPath()
Returns the path as an absolute path
Works with symlinks, which is why it’s different from toAbsolutePath()
Will throw IOException if the path does not exist as an actual file
Files method
Files.exists(Path)
Returns true if it references a file that exists in the file system.
Files method
Files.isSameFile(path1,path2)
Determines if path1 and path2 point to the same file in the filesystem.
Will follow symlinks if necessary
Throws an IOException if either of the files doesn’t exist
Files methods
Files.createDirectory(Path)
Files.createDirectories(Path)
- Creates a directory
- Creates a directory and any nonexistent parent directories specified.
Both can throw IOException if the directory cannot be created or already exists
Files method
Files.copy(path1, path2)
Creates a copy of path1 called path2
For directories it does not copy over the contents to the new place
By default it won’t overwrite any existing files
Throws an IOException if path1 cannot be read or doesn’t exist
What does this code do
try (InputStream is = new FileInputStream(“source-data.txt”);
OutputStream out = new FileOutputStream(“output-data.txt”)) {
Files.copy(is, Paths.get(“c:\mammals\wolf.txt”));
Files.copy(Paths.get(“c:\fish\clown.xsl”), out);
}
- Copies the input stream data to the file wolf.txt
- Copies the data of clown.xsl to the output stream
Files method
Files.move(path1, path2)
Moves or renames path1 to path2 in the file system. Will not overwrite an existing file by default. Will preserve attributes by default.
throws the checked IOException in the event that the file or directory could not be found or moved.
Files methods
Files.delete(path1)
Files.deleteIfExists(path1)
- Deletes the file represented by path1. If path1 is a non-empty directory, then DirectoryNotEmptyException will be thrown. If path1 is a symlink, then the symlink will be deleted, not the file that the symlink points to. Throws NoSuchFileException if path1 doesn’t exist in the file system
- Same as delete(), but will return false if the file doesn’t exist instead of throwing an exception
Files method
Files.newBufferedReader(path1,charset)
Returns a BufferedReader to read in the file represented by path1, using the encoding method specified by charset
Note: Charset.defaultCharset() can be used to make things easy
Files method
Files.newBufferedWriter(path1, charset)
Returns a BufferedWriter to write to the file represented by path1, using the encoding method specified by charset
Files method
Files.readAllLines()
Reads all of the lines of a text file and returns the results as an ordered List of String values.
Throws an IOException if the file cannot be read
Files methods
Files.isDirectory(Path)
Files.isRegularFile(Path)
Files.isSymbolicLink(Path)
- Returns true if is a directory. It will look at what a symbolic link points to if you give it that.
- Return true if not a directory, resource, or some other janky file. It will look at what a symbolic link points to if you give it that.
- Returns true if symbolic link
Files method
Files.isHidden(path1)
Files.isReadable(path2)
Files.isExecutable(path3)
- Returns true if path1 is a hidden file
- Returns true if path2 is readable
- Returns true if path3 is executable
Files method
Files.size(Path)
Returns the size of the file in bytes as a long value.
Files methods
Files.getLastModifiedTime(Path)
Files.setLastModifiedTime(Path,FileTime)
- Returns a FileTime object which contains info on when the file was last modified.
- Sets the last modified time of the file to the specified info in the FileTime object
Both may throw IOException
Note: FileTime has toMillis() and fromMillis() to express the FileTime object as milliseconds from the epoch
Files methods
Files.getOwner(Path)
Files .setOwner(Path,UserPrincipal)
- Returns an instance of UserPrincipal that represents the owner of the file within the file system.
- Set the owner of the file to the UserPrincipal object
Both may throw IOException
View
A group of related attributes for a particular file system type
Files methods
Files.readAttributes(Path, Class)
Files.getFileAttributeView(Path, Class)
- Returns a read-only view of the file attributes.
- Returns the underlying attribute view, and it provides a direct resource for modifying file information.
Both may throw IOException
BasicFileAttributes
The object type that you can store a files attributes in and call methods on to retrieve those attributes
BasicFileAttributes methods
isOther()
fileKey()
- Used to check for paths that are not files, directories, or symbolic links, such as paths that refer to resources or devices in some file systems.
- Returns a file system value that represents a unique identifier for the file within the file system or null if it is not supported by the file system.
BasicFileAttributeView
The object type used to modify a file’s set of date/time values.
BasicFileAttributeView method
setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime)
Used to update the time attributes of the file.
Files method
Files.walk(path)
Returns a Stream object that traverses the directory in a depth-first, lazy manner.
May throw IOException
Files method
Files.find(Path, int, BiPredicate)
Returns a Stream that traverses the directory specified, to a max depth of the int specified, filtering the stream on the BiPredicate provided
Files method
Files.list(Path)
Returns a Stream containing the contents of the directory specified, only to one level, so no traversing down the rest of the structure.
Files method
Files.lines(Path)
Returns a Stream of all the lines in a file