Created
April 5, 2020 14:51
-
-
Save neo7BF/226868182113d88f0b2d96b7a24427f4 to your computer and use it in GitHub Desktop.
Read and Write Objects in java with SerializationUtils of Apache Commons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package it.neo7bf.serialization; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
import org.apache.commons.lang3.SerializationUtils; | |
/** | |
* You must have commons-lang3-3.9.jar in the classpath downloadable here: | |
* https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar | |
*/ | |
public class Main { | |
public static class Impostazioni implements Serializable { | |
private String percorsoSalvataggi = null; | |
public String getPercorsoSalvataggi() { | |
return percorsoSalvataggi; | |
} | |
public void setPercorsoSalvataggi(String percorsoSalvataggi) { | |
this.percorsoSalvataggi = percorsoSalvataggi; | |
} | |
} | |
public static void main(String[] args) { | |
try { | |
/* | |
* Serialization requires simmetric I\O otherwise the exception java.io.OptionalDataException is thrown: | |
* if I write with ObjectOutputStream(FileOutputStream()) I must read | |
* with ObjectInputStream(FileInputStream()) | |
*/ | |
//write mode: ObjectOutputStream(FileOutputStream()) | |
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.dat")); | |
Impostazioni imp = new Impostazioni(); | |
imp.setPercorsoSalvataggi("Insert here save path"); | |
SerializationUtils.serialize(imp, oos); | |
//simmetric read mode: ObjectInputStream(FileInputStream()) | |
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.dat")); | |
Impostazioni newImp = SerializationUtils.deserialize(ois); | |
System.out.println(newImp.getPercorsoSalvataggi()); | |
//prints: Insert here save path | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment