序列化和压缩类到文件

本文关键字:文件 压缩 序列化 | 更新日期: 2023-09-27 18:17:21

我正试图将类写入文件并从文件打开类。这对我很有效;但是,文件大小非常大。(65 MB,压缩成。rar是1MB)。

这让我有理由认为我可以在写入文件之前压缩数据。

我原来的功能是;

public static void save(System system, String filePath){
    FileStream fs = new FileStream(filePath, FileMode.Create);
    try{
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, system);
        fs.Flush();
    }catch(Exception e){
    }finally{
        fs.Close();
    }
}
public static System load(String filePath){
    System system = new System();
    FileStream fs = new FileStream(filePath, FileMode.Open);
    try{
        BinaryFormatter bf = new BinaryFormatter();
        system = (System)bf.Deserialize(fs);
        fs.Flush();
    }catch(Exception e){
    }finally{
        fs.Close();
    }
    return system;
}

为了压缩,我尝试了以下操作,但是在加载到系统类时,这似乎不能正常工作:

public static void save(System system, String filePath){
    FileStream fs = new FileStream(filePath, FileMode.Create);
    try{
        BinaryFormatter bf = new BinaryFormatter();
        DeflateStream cs = new DeflateStream(fs, CompressionMode.Compress);
        bf.Serialize(cs, system);
        fs.Flush();
    }catch(Exception e){
    }finally{
        fs.Close();
    }
}
public static System load(String filePath){
    System system = new System();
    FileStream fs = new FileStream(filePath, FileMode.Open);
    try{
        BinaryFormatter bf = new BinaryFormatter();
        DeflateStream ds = new DeflateStream(fs, CompressionMode.Decompress);
        system = (System)bf.Deserialize(ds);
        fs.Flush();
    }catch(Exception e){
    }finally{
        fs.Close();
    }
    return system;
}

我是否错误地使用了DeflateStream ?我该怎么做才能让它发挥作用呢?

序列化和压缩类到文件

我认为你在save()方法中使用了错误的DeflateStream。您必须要么将其封装在using()中,要么显式地调用Close()以完成其工作。