NIO.2 Flashcards
Which is the entry point for working with NIO.2?
java.nio.file.Path
It represents an heirarchical path to the storage system to a file or directory
What is an additional feature availale with the Path in comparision to the File?
- It has all the features that java.io.File has
2. It also has support for Symbolic links that represents the pointer to another file system
Why is Path an interface in Java if it is the entry point?
Means, why it is not a class so that we could have got the object for it?
Creating a file or a directory is the file-system dependent task in NIO.2.
So, when we get a path object in NIO.2, JVM returns a system specific details for current platform.
Otherwise, we would have to know underlying system platform and develop the code
Name a helper class whose primary objective is to operate on Path object?
java.nio.file.Files, whose primary objective is to operate on instances of Path object
What are the two ways to create a Path object using Paths Class?
- Path path = Paths.get(“c:\”);
- Path path = Paths.get(String, String..)
The second one allows us to create a path from the list of String arguments in which the OS system-dependent separator is automatically inserted between the String arguments.
How can we get the file separator using Path?
System.getProperty(“path.separator”);
Way to create a Path object from URI?
Path path =Paths.get(new URI(“file:///……/../../../.txt”);
URI are string of characters that indicates a resource type. We have to start with schema name. Eg.. http://, ftp://
Path path = Paths.get(“ftp://hello/dilli.txt”);
What is the path here?
It throws runtime exception.
We must only mention absolute path
How to convert a Path instance to the URI instance?
Path path4 = Paths.get(new URI(“http://hellow.com));
URI uri = path4.toUri();
What is the exception thrown by new URI constructor?
URISyntaxException
What is the other way of accessing the Path object without Paths.get()?
Path path = FileSystems.getDefault().getPath(URI);
or
Path path = FileSystems.getDefault().getPath(String, String…)
what is the advantage of using FileSystems for getting the Path object?
- It gives us the ability to connect to the remote file systems.
- When we want to interact frequently with the remote file systems we have to use this technique.
FileSystem fileSystem = FileSystems.getfileSystm(new URI(“http://google.com”));
Path path = fileSystem.getPath(hello.txt);
How the Path interface works with legay file system?
- Converting File object to path:
Path path = file.toPath()
Converting Path to legacy File object:
File file = path.toFile();
which methods represents a String representation of a entir path?
toString() method
Which is the only method in the Path interface that returns a string?
toString()
What is the output of followinig code:
Path path = Paths.get(“C:\Dilli\Dilli.txt”);
System.out.println(path.toString());
for(int i=0; i
C:\Dilli\Dilli.txt
Element 0 is Dilli
Element 1 is Dilli.txt
Will the root element be included in the return values of getName() method?
No, root element will not be included.
- What is the getName(int) index starts from? 0-based or 1-based?
- 0-based
What type is the getName(int) method returns?
Path object
Which method returns the FileName of the Path? What type does it returns>
path.getFileName().
It returns a Path object
getParent() method?
returns the Parent path or null if there is no parent.
Eg.., /zoo/hello/tiger.txt
parent of tiger.txt is /zoo/hello
parent of hello is /zoo
parent of zoo is /
getRoot() method?
- It returns the Root element of the path.
2/ Returns null if the path is absolute
how to check whether the path object is an absolute pr not?
isAbsolute() method. returns true if the path is absolute
returns false if it is not
What is toAbsolutePath() method does?
- Converts a given relative path into an absolute path by appending the current working directory
What if the given path is already absolute path? What does toAbsolutePath() returns?
- It returns an another path object which is the copy of the given absolute path
System.out.println(Paths.get(“/hello/ganesh/Dilli.txt”).isAbsolute());
System.out.println(Paths.get(“C:/hello/ganesh/Dilli.txt”).isAbsolute());
What is the output of this when runs in Windows?
- false
2. true
what is subpath method? what are the arguments it can take
Subpath returns a relative subpath of the Path object.
It takes two int values, an index start and index end
What is the output?
Path path1 = Paths.get(“/mammal/carnivore/racoon.image”);
1. System.out.println(path1.subpath(1, 3)); 2. System.out.println(path1.subpath(0, 3)); 3. System.out.println(path1.subpath(0, 4)); 4. System.out.println(path1.subpath(1, 1));
- carnivore/racoon.image
- mammal/carnivore/racoon.image
- IllegalArgumentException (RunTimeException)
- IllegalArgumentException (RunTimeException)
What needs to be kept on mind for indexing the elements in subpath?
- The root of the Path is not included in the subpath return value
- The directory next to root is the 0-th index element
What are Path symbols?
1) . -> refers to the current directory
2) .. -> refers to the Parent directory (one up directory)
A very cool method to get relation between two Path systems?
relativize(path);
Does the fileExists method throws an Exception?
No, it doesnt throw any exception
What is isSameFile() method does?
useful for determining if two path objects relate to same file.
It also checks if two path objects relate to same directory
When does actual checking of whether file exists happen in isSameFile() method?
- isSameFile() method first checks if the path objects are equal in terms of equal() method, if yes, it automatically returns true without the check of whether file exists.
- If the path objects equals() return false, it locates files in each Path object and determines if they are true, throws IOException if any file doesnt exists
How to create directories with NIO.2 API?
Files.createDirectory(path)
Files.createDirectories(path)
Does the directory creation throws an exception?
- If the directory cannot be created
- If the directory already exists
it throws checked IOException
What is the way to copy a file in NIO.2?
Files.copy(path, path)
and it throws IOException
What should be kept in mind regarding copying Directories.
Directory copy are shallow rather than deep.
Files and Directories within the directories are not copied.
If we need to copy them, we have to traverse them
Copying the files with java.io and NIO.2?
two overloaded methods.
- Files.copy(java.io.InputStream object, path)
- Files.copy(path, java.io.OutputStream)
Which overloaded method supports using the varargs?
- Files.copy(inputStream, path)
What is special about move() method?
moves or rename the files or directory within the file system
What is the default functionality of the move() method?
- move() method follows the links
- move method throws exception if file already existe
- it does not doe atomic move
How to change the default behaviour of the move() method?
NOFOLLOW_LINKS,
REPLACE_EXISTING,
ATOMIC_MOVE
What if the atomic move is not supported in file systm
AtomicMoveNotSupportedException
What are the several restrictions on the movig of directories?
- move method can be applied to non-empty directories only if they are on same underlying drive
- Moving of empty directories across drives are supported
- Moving of non empty directory across drie throws DirectoryNotEmptyException
What does readAllLines() method return?
Ordered list of String values.
Each List contains the String
What are the three methods to find whetehr a path is
- directory
- a regular file and
- Symbolic link
- Files.isDirectory(Path)
- Files.isRegularFile(Path)
- Files.isSymbolicLink(Path)
is it possible for the method isRegularFile(Path) to return true for Symbolic links.
Yes, it can return true as long as the Symbolic link resolves to a regular file
Does isDirectory(), isRegularFile() or isSymbolicLink() throws Exception?
No, they dont throw exceptions
How to find whether a file is hidden in fileSystem?
Files.isHidden() method.
It throws IOException
How to find whether a File/Dircetory is readable or executable?
Files.isReadable(Path)
Files.isExecutable(Path)
It does not thow any exceptions
What is the functionality of Files.size(Path)?
It returns the size of the files in Bytes
How to get the last modified time of the file system?
Files.getLastModifiedTime(Path) which returns a FileTime object to accomplish the task.
FileTime class isa simple container class that stores the information of date/time
What is the method that returns the last modified time in epoch?
FileTime has toMillis() method
How to get the owner of a directory?
Files.getOwner(path)
It returns an instance of UserPrincipal that represents the owner of the file withini the file system
How to set the owner of the directory?
Files.setOwner(path, UserPrincipal)
Do the setOwner and getOwner method throws any exception?
IOException in case of any issues accessing or modifying the ownership
How to set the owner of a file to an arbitrary user in the fileSystem
UserPrincipalOwner owner = FileSystems.getDefault().
getUserPrincipalLookupService().lookupPrincipalByName(user);
NIO2 API provides a UserPrincipalLookupService helper class for finding the UserPrincipal record for a particular user. We need to get the instance of fileSystem with which get the instance of UserPrincipalLookupService to get the UserPrincipal name
What is a view in fileSystems?
A group of related attributes for a particular fileSystem type.
A file may support multiple views allowing you to retrieve and update various sets of information
What are the parameters a method need to request a view.
- Path of the file/Directory whose information you want to read
- A class object, which tells the NIO.2 API which type of view we would like to get returned
What methods does the Files API includes for accessing View informations? Their information
Do they throw any Exceptions and their importance?
Files.readAttributes(path, Class<a>) - that returns read-only view of the file attributes</a>
Files.getFileAttributeView(path, Class</a><a>) returns the underlying attribute view and it provides the direct resource for modifying the information</a>
Both methods throw IOException when a view class type is not supported.
Eg.., Trying to read windows based attributes within the LINUX file system may throw an UnsupportedOperationException</a>
What are the attributes Classes and View Classes?
- BasicFileAttributes, BasicFileAttributeView
- DosFileAttributes, DosFileAttributeView
- PosixFileAttributes, PosixFileAttributeView
What is BasicFileAttributes
All attributes classes extends from BasicFileAttributes class, so they contain all attributes common to all supported Operating systems
What is BasicFileAttributesView
BasicFileAttributeView is used to modify a set of date/time values
What are the basic file Attributes that can be modified?
Only Timme and Date pair
What are the two strategies associated with Walking a directory tree?
- Depth-first search
2. Breadth-first search
Which strtaegy of walking is used by Streams API?
depth-first searching with default Maximum depth of Integer.MAX_VALUE
what is the method (first method) to traverse a directory and what does it returns?
Files.walk(path) that returns a Stream object that traverses a directcory in depth first manner
what method does the Files.walk(path) method follows? Lazy or eager?
Lazy. Until a directory is traversed, its file contents will not be loaded
How many iterations does the walk method iterates by default and how can we change it?
It iterates to the maximum of INTEGER.MAX_VALUE.
There is a overloaded version Files.walk(path, int) that says how many iterations it must do
Does the walk method traverse symbolic links by default? How to change the default behaviur?
It does not traverse Symbolic links by default as it may cause cycles (infinite loops).
We can change this default behaviour by passing ‘FOLLOW_LINKS’ option as vararg to walk method
Does the walk method traverse symbolic links by default? How to change the default behaviur?
It does not traverse Symbolic links by default as it may cause cycles (infinite loops).
We can change this default behaviour by passing ‘FOLLOW_LINKS’ option as vararg to walk method.
If the option is used, the walk()m method will keep track of the path it has traversed, so if it traverse again it throws FilseSystemLoopException
What is the other method that is similar to walk method in a way?
find method.
Files.find(path, int, BiPredicate)
It requires us to explicitly specify the depth value. It also supports FOLLOW_LINK vararg.
What is the alternative method in java,io.File listFiles() method in NIO.2?
Files.list(path).
It outputs the full path of the file in the specified directory
What is the coolest alternative for readAllLines() and how it is coolest?
Files.lines(path). It returns a Stream objectc
It doesnt load entire data into memory as it reads and process lazily.
readAllLines() and lines(). What does they return?
readAllLines() -> List of String
lines() -> Stream object
Can we call forEach on the return list of readAllLines()?
Yes, as Collections supports calling forEach.