Code sample: Writing text to a file

import net.rim.device.api.system.Application;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import java.io.IOException;
import java.io.OutputStream;

public class AddFileContent extends Application 
{
  public static void main(String[] args) 
  {
    AddFileContent app = new AddFileContent();
    app.setAcceptEvents(false);
    try 
    {
      FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/newfile.txt");
      // If no exception is thrown, then the URI is valid, but the file may or may not exist.
      if (!fc.exists())
      {
          fc.create();  // create the file if it doesn't exist
      }
      OutputStream outStream = fc.openOutputStream(); 
      outStream.write("test content".getBytes());
      outStream.close();
      fc.close();
     }
     catch (IOException ioe) 
     {
        System.out.println(ioe.getMessage() );
     }
  }
}

Was this information helpful? Send us your comments.