To use binary serialization and deserialization in Java, first, you need to introduce the relevant packages under java.io, or directly write import java.io.*;
Below, for the convenience of writing operations, we use the method of copying files and throwing exceptions to write
Copy the code code as follows:
public void test6() throws IOException {
byte[] b = new byte[1024];//Define byte array, buffer
FileInputStream in = new FileInputStream("E://logo.gif");//Create an input stream object
FileOutputStream out = new FileOutputStream("E://My.gif");//Create an output stream object
DataInputStream input = new DataInputStream(in);//Create input binary stream
DataOutputStream dout = new DataOutputStream(out);//Create output binary stream
int num = input.read(b);//Read binary file into b
while (num != -1) {
dout.write(b, 0, num);//Write the read array to the output stream
num = input.read(b); // Read again
}
//Close all stream objects in order
input.close();
dout.close();
in.close();
out.close();
System.out.println("Copy successfully!");
}
The code is abbreviated for reference only!
C# uses binary serialization and deserialization operations. First, introduce the namespace using System.Runtime.Serialization.Formatters.Binary; to operate serialization and deserialization. Also, in the class of custom classes involving serialization Add an indicator class [Serializable] above
Example:
[Serializable]
Copy the code code as follows:
public class PlayManager
{
/// <summary>
///Serialize and save data
/// </summary>
public void Save()
{
FileStream fs = null;
try
{
fs = new FileStream("Path to save the file", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, object to be saved);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fs.Close();
}
/// <summary>
/// Load serialization information
/// </summary>
public void Load()
{
FileStream fs = null;
try
{
fs = new FileStream("File Path", FileMode.OpenOrCreate);
BinaryFormatter bf = new BinaryFormatter();
Object receiving = (type of object)bf.Deserialize(fs); //Forced type conversion
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fs.Close();
}
This is the use of serialized files in C#. In fact, this is quite simple. If you don’t add try-catch-finally, it only takes four sentences of code.
Friends who have passed by, do you understand? If you don’t understand, you can ask questions!