Java Reference
In-Depth Information
FileChannel outChannel = outputFile.getChannel();
// Write the file
try {
outChannel.write(buf); // Write the buffer to the file channel
outputFile.close(); // Close the output stream & the channel
} catch(IOException e) {
e.printStackTrace(System.err);
}
Transferring the string via a view buffer of type CharBuffer is much simpler. The only fly in the ointment
is that the backing ByteBuffer has no knowledge of this. The position for buf is still sitting firmly at zero
with the limit as the capacity, so flipping it won't set it up ready to write to the channel. However, all we have
to do is to set the limit corresponding to the number of bytes we transferred to the view buffer.
Of course, if we were writing the file for use by some other program, writing Unicode characters could
be very inconvenient if the other program environment did not understand it. Let's see how we would
write the data as bytes in the local character encoding.
Try It Out - Writing a String as Bytes
We will strip out the directory validation to keep the code shorter:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class WriteAStringAsBytes {
public static void main(String[] args) {
String phrase = new String("Garbage in, garbage out\n");
String dirname = "C:/Beg Java Stuff"; // Directory name
String filename = "byteData.txt";
File aFile = new File(dirname, filename);
// Create the file output stream
FileOutputStream file = null;
try {
file = new FileOutputStream(aFile, true);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
FileChannel outChannel = file.getChannel();
ByteBuffer buf = ByteBuffer.allocate(phrase.length());
byte[] bytes = phrase.getBytes();
buf.put(bytes);
buf.flip();
try {
outChannel.write(buf);
Search WWH ::




Custom Search