How to Save/Restore Serializable Object To/From File

How to save/restore serializable object to/from file?

You can use the following:

    /// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }

try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
}
}
catch (Exception ex)
{
//Log exception here
}
}


/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }

T objectOut = default(T);

try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;

using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);

XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
}
}
}
catch (Exception ex)
{
//Log exception here
}

return objectOut;
}

How to save/restore serializable object to/from file? (part 2) dynamic object

You cannot serialize an object that has not been marked with the Serializable attribute easily, so the short answer is no.

If you're willing to step into moderately difficult code, you could use reflection and devise a custom format to save states with, using exceptions for things like indexed properties, etc.. You might as well just not, though.

How to save/restore serializable object to/from file? (part 2) dynamic object

You cannot serialize an object that has not been marked with the Serializable attribute easily, so the short answer is no.

If you're willing to step into moderately difficult code, you could use reflection and devise a custom format to save states with, using exceptions for things like indexed properties, etc.. You might as well just not, though.

How do I serialize an object and save it to a file in Android?

Saving (w/o exception handling code):

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

Loading (w/o exception handling code):

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();

Is it possible to save/store objects which are in an array in a file?

Yes. You can do that in several ways but the most popular way is that to serialize that array and write it into a file and when you need to retrieve that array from file, than read that certain file and DE-serialized the file content and convert that content to array. One of the most popular way is to use "Newtonsoft.Json" library. Here is my code given below.Please try it and let me know it works or not.

private void ArrayToJSONString(MyClass[] items,string outpath)
{
string jsonData = JsonConvert.SerializeObject(items);
var myFile = File.Create(outpath);
myFile.Close();
File.WriteAllText(@"" + outpath, jsonData);
}
private void JSONStringToArray(string filepath)
{
string jsonData = File.ReadAllText(filepath);
MyClass[] items = JsonConvert.DeserializeObject<MyClass[]>(jsondata);
}

Note: JsonConvert Class is in Newtonsoft.Json Library. It is free and available for both .NET and .NET Core.

How Serializable save object on file edit on it or empties it and fill it again (look to ex)?

It is not possible remove only the part of file. Every time when You make changes in the map, You must to overwrite the whole file. See my example:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class SerializationProgram {

public static void main(String[] args) throws Exception {
emptyTest();
addAndRemoveTest();
}

private static void emptyTest() throws Exception {
ObjectSerializer serializer = new ObjectSerializer();
serializer.serialize(new FileStatus());
FileStatus persisted = serializer.deserialize(FileStatus.class);
test(persisted, new FileStatus());
}

private static void addAndRemoveTest() throws Exception {
ObjectSerializer serializer = new ObjectSerializer();
FileStatus toPersist = new FileStatus();
FileStatus mirror = new FileStatus();

toPersist = serializeDeserializeAndTest(serializer, toPersist, mirror);

File file = new File("/test/test.txt");
Boolean status = Boolean.TRUE;

// Add file status
toPersist.addOrChangeStatus(file, status);
mirror.addOrChangeStatus(file, status);

toPersist = serializeDeserializeAndTest(serializer, toPersist, mirror);

// remove file status
toPersist.removeStatus(file);
mirror.removeStatus(file);

toPersist = serializeDeserializeAndTest(serializer, toPersist, mirror);
toPersist = serializeDeserializeAndTest(serializer, toPersist, mirror);
}

private static FileStatus serializeDeserializeAndTest(
ObjectSerializer serializer, FileStatus toPersist, FileStatus mirror)
throws Exception {
serializer.serialize(toPersist);
toPersist = serializer.deserialize(FileStatus.class);
test(toPersist, mirror);
return toPersist;
}

private static void test(FileStatus given, FileStatus expected) {
if (given.equals(expected)) {
System.out.println("everything is OK");
} else {
throw new IllegalArgumentException("Are not the same!");
}
}
}

class ObjectSerializer {

private static final boolean OVERWRITE_MODE = false;

public <T> void serialize(T instance) throws IOException {
OutputStream overwriteStream = new FileOutputStream(getFile(instance.getClass()), OVERWRITE_MODE);
OutputStream bufferedStream = new BufferedOutputStream(overwriteStream);
ObjectOutputStream objectstream = new ObjectOutputStream(bufferedStream);
objectstream.writeObject(instance);
objectstream.close();
}

@SuppressWarnings("unchecked")
public <T> T deserialize(Class<T> clazz) throws Exception {
InputStream input = new BufferedInputStream(new FileInputStream(getFile(clazz)));
ObjectInputStream objectStream = new ObjectInputStream(input);
T instance = (T) objectStream.readObject();
objectStream.close();
return instance;
}

private <T> File getFile(Class<T> clazz) {
return new File(clazz.getName());
}
}

class FileStatus implements Serializable {

private static final long serialVersionUID = 1L;

Map<File, Boolean> statusMap = new HashMap<File, Boolean>();

public void addOrChangeStatus(File file, boolean status) {
statusMap.put(file, status);
}

public void removeStatus(File file) {
statusMap.remove(file);
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((statusMap == null) ? 0 : statusMap.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FileStatus other = (FileStatus) obj;
if (statusMap == null) {
if (other.statusMap != null)
return false;
} else if (!statusMap.equals(other.statusMap))
return false;
return true;
}
}

How to save/restore serializable object to/from file?

You can use the following:

    /// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }

try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
}
}
catch (Exception ex)
{
//Log exception here
}
}


/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }

T objectOut = default(T);

try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;

using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);

XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
}
}
}
catch (Exception ex)
{
//Log exception here
}

return objectOut;
}

How to save/restore serializable object to/from file?

You can use the following:

    /// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }

try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
}
}
catch (Exception ex)
{
//Log exception here
}
}


/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }

T objectOut = default(T);

try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;

using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);

XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
}
}
}
catch (Exception ex)
{
//Log exception here
}

return objectOut;
}


Related Topics



Leave a reply



Submit