Java,C#使用二進(jìn)制序列化、反序列化操作數(shù)據(jù)
java使用二進(jìn)制序列化、反序列化的操作首先,要引入java.io下面相關(guān)包,或者直接寫import java.io.*;
下面,為了書寫操作的方便,采用復(fù)制文件,和throws聲明異常的方式來寫
public void test6() throws IOException {
byte[] b = new byte[1024];//定義字節(jié)數(shù)組,緩沖
FileInputStream in = new FileInputStream("E:\\logo.gif");//創(chuàng)建輸入流對象
FileOutputStream out = new FileOutputStream("E:\\My.gif");//創(chuàng)建輸出流對象
DataInputStream input = new DataInputStream(in);//創(chuàng)建輸入二進(jìn)制流
DataOutputStream dout = new DataOutputStream(out);//創(chuàng)建輸出二進(jìn)制流
int num = input.read(b);// 讀取二進(jìn)制文件到b中
while (num != -1) {
dout.write(b, 0, num);// 將讀取到的數(shù)組寫入到輸出流
num = input.read(b);// 重新再次讀取
}
// 按順序關(guān)閉所有流對象
input.close();
dout.close();
in.close();
out.close();
System.out.println("復(fù)制成功!");
}
初略代碼,僅供參考!
C#使用二進(jìn)制序列化、反序列化的操作首先,引入命名空間using System.Runtime.Serialization.Formatters.Binary;用以操作序列化和反序列化
還有,在牽涉到序列化的自定義類的類上方加上一個指示類[Serializable]
示例:
[Serializable]
public class PlayManager
{
/// <summary>
/// 序列化保存數(shù)據(jù)
/// </summary>
public void Save()
{
FileStream fs = null;
try
{
fs = new FileStream("保存文件的路徑", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, 要保存的對象);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fs.Close();
}
/// <summary>
/// 加載序列化信息
/// </summary>
public void Load()
{
FileStream fs = null;
try
{
fs = new FileStream("文件路徑", FileMode.OpenOrCreate);
BinaryFormatter bf = new BinaryFormatter();
對象接收= (對象的類型)bf.Deserialize(fs); //強制類型轉(zhuǎn)換
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fs.Close();
}
這就是在C#中序列化文件的使用,其實這個挺簡單的,如果不加try-catch-finally也就四句代碼,
過往的朋友們你們看明白了嗎?不明白的還可以提問哦!
相關(guān)文章
WebUploader+SpringMVC實現(xiàn)文件上傳功能
WebUploader是由Baidu團(tuán)隊開發(fā)的一個簡單的以HTML5為主,F(xiàn)LASH為輔的現(xiàn)代文件上傳組件。這篇文章主要介紹了WebUploader+SpringMVC實現(xiàn)文件上傳功能,需要的朋友可以參考下2017-06-06
Java多線程編程實戰(zhàn)之模擬大量數(shù)據(jù)同步
這篇文章主要介紹了Java多線程編程實戰(zhàn)之模擬大量數(shù)據(jù)同步,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02

