How to write and read java serialized objects into a file
Why not serialize the whole list at once?
FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);
Assuming, of course, that MyClassList is an ArrayList
or LinkedList
, or another Serializable
collection.
In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.
How to write serializable object to String without writing to file?
This would be one way:
try
{
// To String
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(object1);
String serializedObject1 = bos.toString();
os.close();
// To Object
ByteArrayInputStream bis = new ByteArrayInputStream(serializedObject1.getBytes());
ObjectInputStream oInputStream = new ObjectInputStream(bis);
YourObject restoredObject1 = (YourObject) oInputStream.readObject();
oInputStream.close();
} catch(Exception ex) {
ex.printStackTrace();
}
I would prefer the Base64
way though.
This would be an example of encoding:
private static String serializableToString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
And this is an example of decoding:
private static Object objectFromString(String s) throws IOException, ClassNotFoundException
{
byte [] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
return o;
}
De-serializing objects from a file in Java
Try the following:
List<Object> results = new ArrayList<Object>();
FileInputStream fis = new FileInputStream("cool_file.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
results.add(ois.readObject());
}
} catch (OptionalDataException e) {
if (!e.eof)
throw e;
} finally {
ois.close();
}
Following up on Tom's brilliant comment, the solution for multiple ObjectOutputStream
s would be,
public static final String FILENAME = "cool_file.tmp";
public static void main(String[] args) throws IOException, ClassNotFoundException {
String test = "This will work if the objects were written with a single ObjectOutputStream. " +
"If several ObjectOutputStreams were used to write to the same file in succession, " +
"it will not. – Tom Anderson 4 mins ago";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(FILENAME);
for (String s : test.split("\\s+")) {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
}
} finally {
if (fos != null)
fos.close();
}
List<Object> results = new ArrayList<Object>();
FileInputStream fis = null;
try {
fis = new FileInputStream(FILENAME);
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add(ois.readObject());
}
} catch (EOFException ignored) {
// as expected
} finally {
if (fis != null)
fis.close();
}
System.out.println("results = " + results);
}
Serialization: Appending to Object Files in Java
You have to explicitly choose to append to file - otherwise old content will be replaced:
Files.newOutputStream(file, StandardOpenOption.APPEND)
In addition to that, every time you create new ObjectOutputStream new stream is started. You won't be able to read them back using single ObjectInputStream. You can avoid that using this trick
If the file is not too large, it might be a better idea to read all existing objects and then write back existing and new objects using single ObjectOutputStream.
Reading serialized object from a file?
Do this:
myClass readedObject = (myClass) input.readObject();
System.out.println(readedObject);
Writing an serialized object to a file
First of all we can try to write in public directory so results can be easily checked with any file manager app.
Before writing to the filesystem ensure that AndroidManifest.xml
contains two permission requests:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
</manifest>
We can proceed to writing files if your device or emulator/VM running Android 5 or below. If it is not, please take a look at the part of android developer documentation about requesting permissions at runtime.
Here's some code that will give you writable directory with 95% probability:
File destination = new File(Environment.getExternalStorageDirectory(), "My Cool Folder");
destination.mkdirs();
So now you can try to write a file there
fileOutputStream = new FileOutputStream(new File(destination, "outgoings.tmp"));
//write there anything you want
Serialzed Objects Stored in File are not readable
Serialized Objects Stored in File are not readable
They aren't meant to be readable, other than via de-serialization.
The problem is that when I store Serialized Object in a .txt file it's not in readable form and contain some random symbols and letters.
That's not a problem. The only problem is your misplaced expectation that it should be human-readable. There is no specification anywhere that says so.
First of all I would like to know that what's the reason behind that
It is specified in the Object Serialization Stream Protocol.
and then how to solve this problem.
What problem? Your code works correctly. The output in the dialog box put up by StudentReader
is correct:
Name: Asiya Roll No: 58
What you have clearly done here is look directly into the serialized file with some utility program, rather than run your StudentReader
program.
There is no problem here to solve.
NB:
- Closing the object stream closes the underlying file stream. You don't need to close the file stream yourself.
- Serialized objects are not text and should not be saved in .txt files.
Related Topics
Explanation of Generic <T Extends Comparable<? Super T>> in Collection.Sort/ Comparable Code
How to Run MySQL In-Memory for Junit Test Cases
Create Simple Pojo Classes (Bytecode) at Runtime (Dynamically)
Java 8: How to Work with Exception Throwing Methods in Streams
Create Bar Chart in Excel with Apache Poi
Why Does Java Code with an Inner Class Generates a Third Someclass$1.Class File
How to Determine the Primitive Type of a Primitive Variable
Configuration Using Annotation @Springbootapplication
Do Not Use System.Out.Println in Server Side Code
How to Take Screenshots Fast in Java
How to Disable 'X-Frame-Options' Response Header in Spring Security
How to Represent a Range in Java
Java Lambda Returning a Lambda
Parsing Dates of the Format "January 10Th, 2010" in Java? (With Ordinal Indicators, St|Nd|Rd|Th)