Home » Android » java – android what is wrong with openFileOutput?

java – android what is wrong with openFileOutput?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to use openFileOutput function but it doesn’t compile and doesn’t recognize the function. I’m using android sdk 1.6. Is this a sdk problem ? Is this a parameter problem ?

import java.io.FileOutputStream;
public static void save(String filename, MyObjectClassArray[] theObjectAr) {
    FileOutputStream fos;
    try {
        fos = openFileOutput(filename, Context.MODE_PRIVATE);

        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(theObjectAr); 
        oos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
}
How to&Answers:

Your method should be as follows. Takes in an extra Context as a parameter. To this method you can pass your Service or Activity

public static void save(String filename, MyObjectClassArray[] theObjectAr, 
  Context ctx) {
        FileOutputStream fos;
        try {
            fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);


            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(theObjectAr); 
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

Answer:

You’re trying invoke non-static method from static context (your method has static modifier). You either have to make your method to be non-static or to pass in an instance of Context (activity instance in most cases) and invoke the method on the object.

Answer:

Also you can’t openOutputStream on a path. It causes this exception:

java.lang.IllegalArgumentException: File /storage/sdcard0/path/to/file.txt contains a path separator

To fix this you need to create a file object and just create it like this:

String filename = "/sdcard/path/to/file.txt";
File sdCard = Environment.getExternalStorageDirectory();
filename = filename.replace("/sdcard", sdCard.getAbsolutePath());
File tempFile = new File(filename);
try
{
    FileOutputStream fOut = new FileOutputStream(tempFile);
    // fOut.write();
    // fOut.getChannel();
    // etc...
    fOut.close();
}catch (Exception e)
{
    Log.w(TAG, "FileOutputStream exception: - " + e.toString());
}