Java Reference
In-Depth Information
It is very often the case that you want to write strings of different lengths to a file using a channel. In this
case, if you want to recover the strings from the file, you need to provide some information in the file that
allows the beginning and/or end of each string to be determined. A BufferedReader has a readLine()
method that enables strings that are separated by line separators to be read easily, but a channel deals with
mixed character and binary data so you don't have that luxury.
One possibility is to write the length of each string to the file immediately preceding the string itself. This
tells you how many characters there are in a string before you read it. You can use a view buffer to do this.
Let's see how that might work in an example.
TRY IT OUT: Writing Multiple Strings to a File
This example just writes a series of useful proverbs to a file:
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.util.EnumSet;
import java.io.IOException;
import java.nio.ByteBuffer;
public class WriteProverbs {
public static void main(String[] args) {
String[] sayings = {
"Indecision maximizes flexibility.",
"Only the mediocre are always at their best.",
"A little knowledge is a dangerous thing.",
"Many a mickle makes a muckle.",
"Who begins too much achieves little.",
"Who knows most says least.",
"A wise man sits on the hole in his carpet."
};
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("Proverbs.txt");
try {
// Make sure we have the directory
Files.createDirectories(file.getParent());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("New file is: " + file);
// The buffer must accommodate the longest string
// so we find the length of the longest string
Search WWH ::




Custom Search