Write to file from ByteBuffer via channel output is whitespace in Netbeans
/*
* WriteAString.java
*
* Created on May 13, 2007, 10:17 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package StreamExamples;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
*
* @author sdwolf
*/
public class WriteAString {
/** Creates a new instance of WriteAString */
public WriteAString() {
}
public static void main(String[] args) {
String phrase = new String("Garbage in, Garbage out\n");
//String phrase1 = "Garbage in, Garbage out\n"; // test
String dirname = "C:/Beg Java Stuff";
String filename = "charData.txt";
File dir = new File(dirname);
//Now check out the directory
if(!dir.exists()) {
if(!dir.mkdir()) {
System.out.println("Cannot create directory: " + dirname);
System.exit(1);
}
} else if (!dir.isDirectory()) {
System.out.println(dirname + " is not a directory");
System.exit(1);
}
//Create the file stream
File aFile = new File(dir, filename);
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream(aFile, true);
System.out.println("File Stream created successfully");
} catch (FileNotFoundException e) {
e.printStackTrace (System.err);
}
//Create the file output stream channel and the buffer
FileChannel outChannel = outputFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("New buffer: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tCapacity = "
+ buf.capacity());
//Load the data into the buffer
for (char ch : phrase.toCharArray()) {
buf.putChar(ch);
System.out.print(ch);
}
System.out.println("Buffer after loading: position = " + buf.position()
+ "\tLimit = " + buf.limit() + "\tCapacity = "
+ buf.capacity());
//Write the file
try {
outChannel.write(buf); //Write the buffer to a file channel
outputFile.close();//Close the O/P file and channel
System.out.println("Buffer contents written to file");
} catch (IOException e) {
e.printStackTrace (System.err);
}
}
}

