Java Reference
In-Depth Information
Listing 10-8 demonstrates how to write lines of texts to a file using the
write()
method. The program writes a few
lines of text in a file named
twinkle.txt
in the default directory. It prints the path of the file. You may get a different
output when you run this program.
Listing 10-8.
Writing Some Lines of Text to a File in One Shot Using the NIO.2 API
// WriteLinesTest.java
package com.jdojo.nio2;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.nio.file.StandardOpenOption.CREATE;
public class WriteLinesTest {
public static void main(String[] args) {
// Prepare the lines of text to write in a List
List<String> texts = new ArrayList<>();
texts.add("Twinkle, twinkle, little star,");
texts.add("How I wonder what you are.");
texts.add("Up above the world so high,");
texts.add("Like a diamond in the sky.");
Path dest = Paths.get("twinkle.txt");
Charset cs = Charset.forName("US-ASCII");
try {
Path p = Files.write(dest, texts, cs, WRITE, CREATE);
System.out.println("Text was written to " +
p.toAbsolutePath());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Text was written to C:\book\javabook\twinkle.txt
The
Files
class contains
newOutputStream(Path path, OpenOption... options)
that returns an
OutputStream
for the specified
path
. The class contains a
newBufferedWriter(Path path, Charset cs, OpenOption... options)
method that returns a
BufferedWriter
for the specified
path
. You can use the
java.io
API to write contents to a file
using the
OutputStream
and
BufferedWriter
. Please refer to Chapter 7 for more details on how to use the java.io API.
You can use the
newByteChannel(Path path, OpenOption... options)
method to get a
SeekableByteChannel
for the specified
path
. You can use the
write(ByteBuffer src)
method of the
SeekableByteChannel
to write data to a
file. Please refer to Chapter 9 for more details on how to use the channel API to write to a file. I will discuss an example
of using
SeekableByteChannel
in the next section.