Answer the question
In order to leave comments, you need to log in
Having a problem serializing objects in android?
Here are the serialization methods:
public static void writeFileSD(String fileName, Object object, Context context) throws IOException {
// проверяем доступность SD
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.d("", "SD-карта не доступна: " + Environment.getExternalStorageState());
return;
}
File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/" + fileName + ".txt");
patternDirectory.mkdirs();
FileOutputStream fos = new FileOutputStream(new File(patternDirectory.getAbsolutePath().toString()), true);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(object);
os.close();
}
public static Object readFileSD(String fileName, Context context) throws IOException, ClassNotFoundException {
// проверяем доступность SD
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.d("", "SD-карта не доступна: " + Environment.getExternalStorageState());
return null;
}
Object object = null;
File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/" + fileName + ".txt");
patternDirectory.mkdirs();
FileInputStream fis = new FileInputStream(new File(patternDirectory.getAbsolutePath().toString()));
ObjectInputStream is = new ObjectInputStream(fis);
object = is.readObject();
is.close();
return object;
}
Answer the question
In order to leave comments, you need to log in
Did it like this:
public static void writeFileSD(String fileName, Object object) throws IOException {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
sdPath = new File(sdPath.getAbsolutePath(), DIR_SD);
sdPath.mkdirs();
File sdFile = new File(sdPath, fileName);
FileOutputStream fileOutputStream = new FileOutputStream(sdFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
}
public static Object readFileSD(String fileName) throws IOException, ClassNotFoundException {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return null;
}
Object object = null;
File sdPath = Environment.getExternalStorageDirectory();
sdPath = new File(sdPath.getAbsolutePath() + "/" + DIR_SD);
File sdFile = new File(sdPath, fileName);
FileInputStream fileInputStream = new FileInputStream(sdFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
object = objectInputStream.readObject();
objectInputStream.close();
return object;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question