Java Reference
In-Depth Information
directory is created in the target location, but the entries in the directory are not copied. You
will see later how to easily copy over a complete directory using this method.
Path move(Path source, Path target, CopyOptions... options) : Moves a source
file to a target file. The options specify how the move is performed. By default, the move
operation will fail if the target file already exists (except when both are the same file), unless
you pass REPLACE_EXISTING as an option. If the file to copy is a directory, the move will be
successful if the directory is empty. Otherwise, the result of the move depends on the underly-
ing file system and can throw an IOException in some cases. In that case, a copy should be
performed first followed by a manual cleanup of the original source directory.
Note Note that these methods provide a more straightforward means to
copy and move files than the stream-based file copy programs you've seen
before. Again, one of the nice improvements of the NIO2 API.
Reading, Writing, and Creating Files
Next, let's take a look at how to read, write, and create files using the NIO2 API. In this chapter,
you've already seen how to use stream-based methods to do this, and the NIO2 API will build on
the concept of streams, while also making our lives easier with some helpful methods.
First of all, when you just want to get all bytes or lines from a file, you can use the following
methods:
byte[] Files.readAllBytes(Path path) : Reads all the bytes from a file to a byte array.
This method takes care of opening and closing the file for you.
List<String> readAllLines(Path path, Charset cs) : Reads all lines from a file to a
list of strings. This method takes care of opening and closing the file for you. The Charset
parameter specifies which character set should be used for decoding the file. Using Charset.
defaultCharset() or Charset.forName("UTF-8") works best in most cases.
Note, however, that these methods will read the complete contents of a file at once, and thus will fail
to work when you are dealing with large files. For small files, however, this approach is straightfor-
ward and works just fine. As an example, recall the grocery-reading application we showed off in the
introduction. Note that you can completely avoid dealing with streams thanks to the Files class:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ShowGroceries {
public static void main(String[] args) {
List<String> groceries = new ArrayList<>();
Search WWH ::




Custom Search