problem with file output using NetBeans
Hi Folks....I am running this code in NetBeans. It executes without complaint. The directory and file are created just fine. The code is designed to append the File, which it does. But the contents of the file is always whitespace. Each time I run it the file ( charData.txt ) increases in size by about 1 KB. Is this a problem with NetBeans or the code, etc....?Thank you...
/*
* 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
*/
publicclass WriteAString{
/** Creates a new instance of WriteAString */
public WriteAString(){
}
publicstaticvoid 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);
}
}elseif (!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);
}
}
}

