Saturday, September 5, 2015

J2ME FileConnection Gotchas: Overwrite and beginning with .

J2ME gives you all the power of what was in a 1997 PC to put apps on billions of phones: with none of the debugging tools.

1. Nokia Series 40 will now allow you to create a filename that begins with "." - do that and you will get an exception .

2. Even in the emulator: if you want to overwrite the entire file when getting an output stream to an existing file: the only way I have seen consistent results is to delete the file first.  Incredibly even openOutputStream(0) - to explicitly open the outputstream at the start seemed to overwrite some but not all of the file (e.g. if you want to overwrite with a smaller file than it was originally there will be trailing leftovers from the previous file).  Something like this works:

public OutputStream openFileOutputStream(String fileURI, boolean autocreate) throws IOException{
        FileConnection con = null;
        IOException e = null;
        try {
            con = (FileConnection)Connector.open(fileURI, Connector.READ_WRITE);
            if(con.exists()) {
                con.delete();
            }
                
            con.create();
        }catch(IOException e2) {
            e = e2;
        }finally {
            J2MEIOUtils.closeConnection(con);
            if(e != null) throw e;
        }
        
        
        OutputStream out = Connector.openOutputStream(fileURI);
        return out;        
    }