Java NIO files examples


In Java 8, there are several new methods added to the java.nio.file.Files class that make it easier to read and write files using the new stream API. Here are some examples:

Read file contents to a string:

String contents = new String(Files.readAllBytes(Paths.get("filename.txt")));

Read file contents to a list of strings (one line per element):

List<String> lines = Files.lines(Paths.get("filename.txt")).collect(Collectors.toList());

Write a string to a file:

String content = "Hello, World!";
Files.write(Paths.get("filename.txt"), content.getBytes());

Write a list of strings to a file (one element per line):

List<String> lines = Arrays.asList("line 1", "line 2", "line 3");
Files.write(Paths.get("filename.txt"), lines);

Append a string to an existing file:

String content = "Hello, World!";
Files.write(Paths.get("filename.txt"), content.getBytes(), StandardOpenOption.APPEND);

Delete a file:

Files.delete(Paths.get("filename.txt"));

Note that these methods throw IOException in case of any I/O error. Also, it’s important to close the stream after using it to avoid any resource leaks.