writeObject(this)无法写入对象,java

时间:2014-04-24 14:40:00

标签: java objectoutputstream

我正在使用ObjectOutputStream来保存对象,但是当我使用.writeObject(this)将其保存为文件时,无法保存该材料。我定义的类已经可序列化了。

public class LanguageModel implements Serializable {


private static LanguageModel lm_;

/* ******************************* */
//word -> count(w)
public static Dictionary unigramDict = new Dictionary();
//word_pair -> count(wi,wi+1)
public static Dictionary bigramDict = new Dictionary();

private static int wordIdCounter = 0;
/* ***************************** */


// Do not call constructor directly since this is a Singleton
private LanguageModel(String corpusFilePath) throws Exception {
    constructDictionaries(corpusFilePath);
}


public void constructDictionaries(String corpusFilePath)
        throws Exception {

    ...
    }

// Saves the object (and all associated data) to disk
public void save() throws Exception{
    FileOutputStream saveFile = new FileOutputStream(Config.languageModelFile);
    ObjectOutputStream save = new ObjectOutputStream(saveFile);
    save.writeObject(this);
    save.close();
}

// Creates a new lm object from a corpus
public static LanguageModel create(String corpusFilePath) throws Exception {
    if(lm_ == null ){
        lm_ = new LanguageModel(corpusFilePath);
    }
    return lm_;
}

}

我定义的课程如下:

import java.io.Serializable;

import java.util.HashMap;

public class Dictionary implements Serializable {

private int termCount;
private HashMap<String, Integer> map;

public int termCount() {
    return termCount;
}

public Dictionary() {
    termCount = 0;
    map = new HashMap<String, Integer>();
}

...
}

当我尝试save.writeObject(unigramDict)时,它可以正确保存此变量。由于它是一个大变量,我可以简单地检查文件的大小。它是5MB。当我切换到save.writeObject(this)时,文件的大小只有53字节。

1 个答案:

答案 0 :(得分:5)

我认为您在使用save.writeObject(this)保存的静态字段时遇到问题。

来自ObjectOutputStream javadoc:

  

对象的默认序列化机制会写入类   对象,类签名和所有非瞬态的值   和非静态字段。

您只需将unigramDictbigramDict设置为非静态字段,然后使用LangugageModel.lm_.unigramDict进行访问。
也许您可以查看singleton pattern,而不是将所有字段设置为static