Java Reference
In-Depth Information
System.err.println("Error creating directory: " +
file.getParent());
e.printStackTrace();
System.exit(1);
}
System.out.println("New file is: " + file);
ByteBuffer buf = null;
// Buffer to hold a
saying
try(WritableByteChannel channel =
Files.newByteChannel(file, EnumSet.of(CREATE,
WRITE))){
// Write sayings to the file
for(String saying : sayings) {
// Saying & separator in buffer
buf = ByteBuffer.wrap((saying + separator).getBytes());
channel.write(buf);
}
System.out.println("File written.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
TryChannel.java
The
file
path will be created in your user home directory.
The only output is the file path and a message confirming that the file has been written, but you should be
able to inspect the contents of the
MoreSayings.txt
file that is created in the
Beginning Java Stuff
directory. If you are using Microsoft Windows, Notepad does it.
How It Works
You obtain the newline separator for the system by calling the static
lineSeparator()
method in the
System
class. You append this to each string to separate the strings in the file. Defining the path and cre-
ating the directory if necessary is as you have seen before.
The
FileChannel
object is created in the
try
block using the static
newByteChannel()
method in the
Files
classed. The reference that is returned is stored as type
WritableByteChannel
because the op-
tions you specified determine that the file is only opened for writing. Storing the reference as a
Writ-
ableByteChannel
reference restricts the methods available to just the
write()
method that the
Writ-
ableByteChannel
interface declares.
The data to be written to the file has to be in a
ByteBuffer
object to allow it to be written by the channel.
The
getBytes()
method in the
String
class converts the characters in a string to bytes using the default
Charset
for your environment. You apply this method in the loop to each string from the
sayings
array
with a line separator appended to it. The static
wrap()
method in the
ByteBuffer
class creates a buffer
that wraps the bytes from the
byte
array that you pass as the argument.