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;
}
}
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 yearsFile
constructorboolean
that is always true
getFD().sync()
on a FileOutputStream
to confirm all bytes are written to disk