我使用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_;
}
}
Run Code Online (Sandbox Code Playgroud)
我定义的类如下:
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>();
}
...
}
Run Code Online (Sandbox Code Playgroud)
当我尝试时save.writeObject(unigramDict),它可以正确保存此变量.由于它是一个大变量,我可以简单地检查文件的大小.它是5MB.当我切换到save.writeObject(this),文件的大小只有53字节.
我认为你遇到了无法保存的静态字段save.writeObject(this).
来自ObjectOutputStreamjavadoc:
对象的默认序列化机制会写入对象的类,类签名以及所有非瞬态和非静态字段的值.
您应该简单地设置unigramDict和bigramDict作为非静态字段,并使用它来访问它LangugageModel.lm_.unigramDict.
也许您可以查看单例模式而不是将所有字段设置为static.
| 归档时间: |
|
| 查看次数: |
1073 次 |
| 最近记录: |