Consider the following program:
import java.nio.file.*; public class Main { public static void main(String[] args) { Path aFilePath = Paths.get("D:\\dir\\file.txt"); // FILEPATH while(aFilePath.iterator().hasNext()) { System.out.println("path element: " + aFilePath.iterator().next()); }//ww w.j a v a2 s. co m } }
Assume that the file D:\dir\file.txt exists in the underlying file system.
Which one of the following options correctly describes the behavior of this program?
path element: dir path element: file.txt
C)
In the while loop, you use iterator()
to get a temporary iterator object.
So, the call to next()
on the temporary variable is lost, so the while loop gets into an infinite loop.
In other words, the following loop will terminate after printing the "dir" and "file.txt" parts of the path:.
Iterator<Path> paths = aFilePath.iterator(); while(paths.hasNext()) { System.out.println("path element: " + paths.next()); }
Option A) is wrong because the Paths.get method does not throw FileNotFoundException.
Option B) is wrong because InvalidPathException is a RuntimeException. Also, since the file path exists in the underlying file system, this exception will not be thrown when the program is executed.
Option D) is wrong because the program will get into an infinite loop).