Reputation: 976
I'm trying to write a file on SD Card but I'm unable to do it. Can you help me debug the code?
In the Method WriteToFile
at this line it's getting exception FileOutputStream fos = new FileOutputStream(fileWithinMyDir);
.
package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
public class LauncherFileOperations {
public void writeToFile(Context context, Object object, String directoryName, String fileName)
{
try{
File mydir = new File(Environment.getExternalStorageDirectory() + directoryName); //Creating an internal dir;
if(!mydir.exists())
mydir.mkdir();
File fileWithinMyDir = new File(mydir, fileName+".pList"); //Getting a file within the dir.
FileOutputStream fos = new FileOutputStream(fileWithinMyDir);
ObjectOutputStream oos = new ObjectOutputStream(fos); //Select where you wish to save the file...
oos.writeObject(object); // write the class as an 'object'
oos.flush(); // flush the stream to insure all of the information was written to 'save.bin'
oos.close();// close the stream
}
catch(Exception ex) {
Log.v("LauncherFile OPerations.. writeFailed to Launcherfile",ex.toString());
}
}
public Object readFromFile(Context context, String directoryName, String fileName) {
Object o = null;
try{
File mydir = new File(Environment.getExternalStorageDirectory() + directoryName); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, fileName+".pList"); //Getting a file within the dir.
FileInputStream fis = new FileInputStream(fileWithinMyDir);
ObjectInputStream ois = new ObjectInputStream(fis);
o = ois.readObject();
ois.close();
}
catch(Exception ex) {
Log.v("LauncherFile operations..readFailed ",ex.toString());
}
return o;
}
}
Upvotes: 0
Views: 234
Reputation: 1571
File mydir = new File(Environment.getExternalStorageDirectory() + "/" +directoryName); //Creating an internal dir;
if(!mydir.exists())
mydir.mkdir();
File fileWithinMyDir = new File(mydir, fileName+".pList"); //Getting a file within the dir.
FileOutputStream fos = new FileOutputStream(fileWithinMyDir);
I think you have to give "/" for the folder structure.. And if you have more then one folders please use mkdirs().
Upvotes: 1