1

I am searching in google and can not find a true answer to my question ! my question is same as him but his want MODE_APPEND and i want MODE_PRIVATE for my file.how should i do ?

this is my code :

public boolean saveCustomButtonInfo (Context context, Vector<DocumentButtonInfo> info) throws Exception{
    String path= context.getFilesDir() + "/" + "Load";
    File file = new File(path);

    if(! file.exists()){
        file.mkdir();
        //Toast.makeText(context,file.getAbsolutePath(),Toast.LENGTH_LONG).show();
     }
    path=path+"/DocumentActivityCustomButtonsInfo.obj";
    try{
        FileOutputStream out=context.openFileOutput(path,Context.MODE_PRIVATE);
        ObjectOutputStream outObject=new ObjectOutputStream(out);
        outObject.writeObject(info);
        outObject.flush();
        out.close();
        outObject.close();
        return true;
    }catch(Exception ex){
        throw ex;

    }
}
Community
  • 1
  • 1
MrNadimi
  • 1,424
  • 4
  • 18
  • 33

1 Answers1

3

You cannot use paths with slashes (/) with openFileOutput(). More importantly, you are trying to combine both getFilesDir() and openFileOutput(), which is unnecessary and is causing this problem.

Change your code to:

public void saveCustomButtonInfo (Context context, List<DocumentButtonInfo> info) throws Exception {
    File dir = new File(context.getFilesDir(), "Load");

    if(! dir.exists()){
        dir.mkdir();
    }
    File f = new File(dir, "DocumentActivityCustomButtonsInfo.obj");
    FileOutputStream out=new FileOutputStream(f);
    ObjectOutputStream outObject=new ObjectOutputStream(out);
    outObject.writeObject(info);
    outObject.flush();
    out.getFD().sync();
    outObject.close();
}

Of note:

  • Vector has been obsolete for ~15 years
  • Never use concatenation to build filesystem paths; use the proper File constructor
  • There is no point in catching an exception only to just re-throw it
  • There is no point in returning a boolean that is always true
  • Call getFD().sync() on a FileOutputStream to confirm all bytes are written to disk
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • thank you for the best answer . i know Vector has been obsolete but thats easier than ArrayList . and the boolean value for checking the true operation . – MrNadimi Dec 10 '16 at 14:41