6. Java 7: File NIO2 Flashcards Preview

Upgrade: Java 8 > 6. Java 7: File NIO2 > Flashcards

Flashcards in 6. Java 7: File NIO2 Deck (36)
Loading flashcards...
1
Q
How would you write the following code to point to a file path using Java 7 new features?
File file = new File("readme.txt");
A

Path path = Paths.get(“readme.txt”);

2
Q
Given the following code, how can a File be converted to a Path object?
File file = new File("readme.txt");
A

file.toPath();

3
Q

Given the following code what will be printed?
Path path = Paths.get(“//home/user/jordi”);
System.out.println(path.toString());

A

/home/user/jordi

Paths.get or FileSystem.getDefault().getPath will preform minor syntatic cleanup on paths.

4
Q

Given the following file path how would one loop over the directories and print them?

/home/user/jordi/readme.txt

A

Path path = Paths.get(“/home/user/jordi/readme.txt”);
for(int i = 0; i < path.getNameCount; i++) {
System.out.println(path.getName(i));
}

5
Q

Given the following path how would you print the filename?

Path path = Paths.get(“//home/user/jordi/readme.txt”);

A

path.getFileName();

6
Q

What is the result of subPath?
Path path = Paths.get(“//home/user/jordi/readme.txt”);
Path subPath = path.subPath(0,2);

A

/home/user

7
Q

What is the result of root?
Path path = Paths.get(“./user/jordi”);
Path root = path.getRoot();

A

null

path.getRoot(); is only usefull when using absolute paths. For example if the path (on windows) would have been C:\users it would have returned C:\

8
Q

Given the following how would one replace jordi with bar?

Path path = Paths.get(“/user/jordi”);

A

path.resolveSibling(“bar”);

9
Q

Given the following code, what is printed?
Path path = Paths.get(“/user/jordi/../../foo”);
path.normalize();
System.out.println(path.getNameCount());
System.out.println(path.toString());

A

5
/foo

Normalize will remove redundant paths from the complete path. However the getNameCount(); will still return the orignal number of Name parts.

10
Q
What is the result of the following:
Path p1 = Paths.get("home");
Path p2 = Paths.get("home/users/jordi");
Path relative_1_2 = p1.relativize(p2);
Path relative_2_1 = p2.relativize(p1);
A

users/jordi

../..

11
Q

How would one move into a sub-directory using a path?

A

path.resolve(“subdir”);

12
Q

What is the Files class used for?

A

Class with static methods that uses Path objects to work with files and folders.

13
Q

What are the available options when using Files to do a copy operation?

A

LinkOption.NOFOLLOW_LINK
Indicates that if the file is symbolic link it should copy the link and not the file linked to.
StandardCopyOption.COPY_ATTRIBUTES
Copies the originals file attributes to the new file, the attributes are platform independent but the last-modified-time is supported accross platform.
StandardCopyOption.REPLACE_EXISTING
Performs the copy operation even if the target file already exists.If the target is a non-empty directory the copy fails with FileAlreadyExistsException.

14
Q

How to copy a file from /home/readme.txt to /home/readme2.txt using the FIles class? The last modified time should also be copied to the new file and existing files should be overwritten.

A

Path p1 = Paths.get(“/home/readme.txt”);
Path p2 = Paths.get(“/home/readme2.txt”);
Files.copy(p1, p2, StandardCopyOption.COPY_ATTRIBUTES,
StandardCopyOption.REPLACE_EXISTING
);

15
Q

What are the available options when using Files to do a move operation?

A

StandardCopyOption.REPLACE_EXISTING
Performs the copy operation even if the target file already exists.If the target is a non-empty directory the copy fails with FileAlreadyExistsException.
StandardCopyOption.ATOMIC_MOVE
It will move the file into a directory any process watching the directory will only access the file when it’s completly moved (not partially). Throws a exception when a ATOMIC_MOVE is not supported by the filesystem.

16
Q

How to move a file from /home/readme.txt to /readme2.txt using the Files class? It should replace any already existing files.

A
Path p1 = Paths.get("/home/readme.txt");
Path p2 = Paths.get("/readme2.txt");
Files.move(p1, p2,
StandardCopyOption.REPLACE_EXISTING
);
17
Q

What is the result of the following (given p1 and p2 are valid Path objects):
Files.move(p1, p2,
StandardCopyOption.COPY_ATTRIBUTES
);

A

throws UnsupportedOperaionException

COPY_ATTRIBUTES is not a valid option for move.

18
Q

How to use the Files class to read all bytes from a file names /home/readme.txt?

A

Path p1 = Paths.get(“/home/readme.txt”);

byte[] bytes = Files.readAllBytes(p1);

19
Q

Files class provides two methods for creating a BufferedReader and a BufferedWriter, name these two method signatures.

A

Files.createNewBufferedReader(Path path, Charset cs, OpenOption… options);
Files.createNewBufferedWriter(Path path, Charset cs, OpenOption… options);

20
Q

How to create an InputStream using the Files class for file /home/readme.txt.

A
Path p1 = Paths.get("/home/readme.txt");
Files.newInputStream(p1);
21
Q

The Files class methods sometimes take none or more OpenOptions. What are the StandardOpenOptions?

A

APPEND - When opened for WRITE, append new bytes to the end of the file.
CREATE - Create a new file if it doesn’t exist. Ignored if CREATE_NEW is also present
CREATE_NEW - Create a new file, fails if the file already exists.
DELETE_ON_CLOSE - When the JVM closes the file it will do a best effort to try and delete the file (not guaranteed).
DSYNC - Requires that every change of the data is synchronously written to the underlying storage device.
SYNC - Requires that every change of the date or metadat is synchronously written to the underlying storage device.
READ - Open for read access.
SPARSE - when used with CREATE_NEW then it will mark the file as a Sparse file (only possiible if the File system supports it).
TRUNCATE_EXISTING - if opened with WRITE access the file will be emptied on open.
WRITE - Open for write access.

22
Q

How would one open a directory called /home and loop ofer it’s contents that end with .java?

A
Path p1 = Paths.get("/home");
Files.newDirectoryStream(p1, *.java);
23
Q

Name the two methods for creating temp files using the Files class?

A

createTempFile(String prefix, String suffix, FileAttribute>… atrs);
- Create a temp file using the default directory. The prefix and suffix can be used to control the filename that is generated. For example if prefix is myapp_ and suffix is .myapp then the generated filename could be myapp_182391082930.myapp.
createTempFile(Path dir, String prefix, String suffix, FileAttribute>… atrs);
-Creates a temp file in the specified dir.

24
Q

Describe the interface to recursively access a directory tree?

A
public interface FileVisitor {
FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) throws IOException;
FileVisitResult visitFile(T file, Basic, BasicFileAttributes attrs) throws IOException;
FileVisitResult visitFileFailed(T file, IOException e) throws IOException;
FileVisitResult postVisitDirectory(T dir, IOException e) throws IOException;
}
25
Q

Describe the FileVisitResult interface?

A

CONTINUE
- Continue. When returned from preVisitDirectory then the entries of the dir should also be visited.
TERMINATE
- Terminate the process.
SKIP_SUBTREE
- Continue without visiting the entries in this directoory. Only meaninful when returned from the preVisitDirectory method.
SKIP_SIBLINGS
- Continue without visiting the siblings of this file or directory.

26
Q

Use a SimpleFileVisitor to loop through the directories and files of the following directory tree and print the path and the size:

/home
/home/readme.txt
/home/jordi/
/home/jordi/readme2.txt

A
FileVisitor visitor = new SimpleFileVisitor() {
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
   System.out.println(dir.toString() + "-" attrs.size());
   return FileVisitResult.CONTINUE;
}

public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
System.out.println(file.toString() + “-“ + attrs.size());
return FileVisitResult.CONTINUE;
}
}

Paths.walkFileTree(Paths.get(“/home”), visitor);

27
Q

How to create a PathMatcher using the default filesystem and based on glob pattern matching?

A

FileSystem fs = FileSystems.getDefault();

fs.getPathMatcher(“glob:” + pattern);

28
Q

Given a Path object how to use a PathMatcher to print if it matches against the glob pattern for either a java or class file?

A

FileSystem fs = FileSystems.getDefault();
PathMatcher matcher = fs.getPathMatcher(“glob:*.{java,class}”);
System.out.println(matcher.matches(Path.get(“/home”));

29
Q

Descirbe how to create a file watcher that watches the directory “/home/jordi” for create and modify events

A
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("/home/jordi");
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
30
Q

What are the events that can be listened to using a WatchService?

A

StandardWatchEventKinds.ENTRY_CREATE
StandardWatchEventKinds.ENTRY_MODIFY
StandardWatchEventKinds.ENTRY_DELETE
StandardWatchEventKinds.OVERFLOW

31
Q

What are the three WatchService methods to retrieve a WatchKey with the events that occured?

A

WatchService.poll(); returns and removes the next WatchKey that has had some its events occur or NULL if no events occurred.
WatchService.polll(long timeout, TimeUnit unit); If an event occurs during the specified time period this method exits and returning and removing the relevant WatchKey.
WatchService.take() similair to preceding methods but will wait until a watchkey is available.

32
Q

What are the states a WatchKey can ben in?

A

Ready - When first created.
Signalled - indicates that one or more events are queued.
Invalid - The key is no longer active. This happens when
* cancel() is called on the WatchService.
* The directory becomes inaccessible
* The watch service is closed.

33
Q

How to get the events from a WatchKey?

A

pollEvents();

returns a list of occured events.

34
Q

What is the result:
WatchKey key = watchService.take(); //waits until a key is available
System.out.println(key.isValid());
for (WatchEvent> watchEvent : key.pollEvents()) {
Kind> kind = watchEvent.kind();
}
System.out.println(key.isValid());

A

true true

A WatchKey does not become invalid until it is cancelled or the WatchService is closed.

35
Q

Which of the following statements are valid usages of StandardOpenOption options that determine how the file is opened?

  1. new OpenOption[]{StandardOpenOption.WRITE, StandardOpenOption.DSYNC}
  2. new OpenOption[]{StandardOpenOption.READ, StandardOpenOption.APPEND}
  3. new OpenOption[]{StandardOpenOption.APPEND, StandardOpenOption.TRUNCATE_EXISTING}
  4. new OpenOption[]{StandardOpenOption.APPEND, StandardOpenOption.SYNC}
  5. new OpenOption[]{StandardOpenOption.READ, StandardOpenOption.SYNC}
A

1,4,5

36
Q

What is the result of the following?
Path p1 = Paths.get(“\personal\readme.txt”);
Path p2 = Paths.get(“\index.html”);
Path p3 = p1.relativize(p2);
System.out.println(p3);

A

....\index.html