Search code examples
androidruntime-errorillegalargumentexceptionpath-separator

IllegalArgumentException: File contains a path separator Android


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;

    }
}

Solution

  • 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