Reputation: 3199
I have main activity where I'm creating a new object called fileSaver. I'm trying to sarialize object 'data' to file. FileSave has a method serialize() which creates file.
private String FILE_NAME = "file.dat";
FileSaver fileSaver = new FileSaver();
Data data = new Data();
data.setEmail("[email protected]");
fileSaver.serialize((Object) data,FILE_NAME);
The problem is that I can't create a file outside activity. When I try the same inside activity, it creates that file. I was experimenting with paths but without success. I know when the file is created from activity it is saved in /data/data/my_package_name/files but how to access that file from outside activity class?
Class FileSaver:
public class FileSaver {
public void serialize(Object objToSerialize,String fileName) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(fileName));
out.writeObject(objToSerialize);
out.close();
System.out.println("Object : " + objToSerialize.getClass()
+ " serialized successfully");
} catch (Exception ex) {
System.out.println("Error Saving Object to File :"
+ ex.getMessage());
ex.printStackTrace();
}
}
}
Thank you.
Upvotes: 2
Views: 1270
Reputation: 442
You can save the file in the SDCARD instead.
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+filename));
//here filename is your input filename in String and Environment.getExternalStorageDirectory() gives you the SDCard directory.
Also make sure you add the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the Android Manifest file
Upvotes: 0
Reputation: 2263
you have to pass context to outside java class and using the context, use this openFileOutput() method to create and write a file in android device memory
Upvotes: 1