Java Reference
In-Depth Information
import java.nio.charset.Charset;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
public class ReadAllLines {
public static void main(String[] args) {
Charset cs = Charset.forName("US-ASCII");
Path source = Paths.get("luci1.txt");
try {
// Read all lines in one go
List<String> lines = Files.readAllLines(source, cs);
// Print each line
for (String line : lines) {
System.out.println(line);
}
}
catch (NoSuchFileException e) {
System.out.println(source.toAbsolutePath() + " does not exist.");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Writing to a File
The NIO.2 API supports writing to a file in the following three ways:
Writing an array of bytes or a collection of lines of texts to a file in one shot.
OutputStream and a BufferedWriter using the java.io API.
Writing to a file using an
SeekableByteChannel object.
You can use the following write() methods of the Files class to write contents to a file in one shot:
Writing to a file using the channel API using a
static Path write(Path path, byte[] bytes, OpenOption... options)
static Path write(Path path, Iterable<? extends CharSequence> lines,
OpenOption... options)
static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs,
OpenOption... options)
These methods are designed to write smaller contents to a file. You are advised to use other methods
(discussed below) to write bigger contents to a file.
The write() method opens the file, writes the passed in contents to the file, and closes it. If no open options are
present, it opens the file with CREATE , TRUNCATE_EXISTING , and WRITE options. If you are writing lines of text to a file,
it writes a platform-dependent line separator after every line of text. If charset is not specified when lines of text are
written, UTF-8 charset is assumed.
 
Search WWH ::




Custom Search