Java Reference
In-Depth Information
The code creates a string from the text inserting a platform-dependent new line character between two lines.
It converts the text into a byte array, creates a byte buffer by wrapping the byte array, and writes the buffer to the file
channel. Note that you do not need to use the flip() method on the buffer because, before passing it to the channel for
writing, your buffer object was just created with the text, and its position and limit were set appropriately by the wrap()
method. The program prints the path of the file in which the text was written that may be different on your machine.
Listing 9-8. Writing to a File Using a Buffer and a Channel
// FileChannelWrite.java
package com.jdojo.nio;
import java.io.File;
import java.nio.channels.FileChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.io.FileOutputStream;
public class FileChannelWrite {
public static void main(String[] args) {
// The output file to write to
File outputFile = new File("luci5.txt");
try (FileChannel fileChannel =
new FileOutputStream(outputFile).getChannel()) {
// Get the text as string
String text = getText();
// Convert text into byte array
byte[] byteData = text.toString().getBytes("UTF-8");
// Create a ByteBuffer using the byte array
ByteBuffer buffer = ByteBuffer.wrap(byteData);
// Write bytes to the file
fileChannel.write(buffer);
System.out.println("Data has been written to " +
outputFile.getAbsolutePath());
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static String getText() {
String lineSeparator = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
sb.append("In one of those sweet dreams I slept,");
sb.append(lineSeparator);
sb.append("Kind Nature's gentlest boon!");
sb.append(lineSeparator);
Search WWH ::




Custom Search