package com.corpus;
import java.io.*;
import java.util.List;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.Sentence;
import edu.stanford.nlp.ling.TaggedWord;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
public class testFile {
/**
* @param args
* @throws IOException
* @throws IOException
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
MaxentTagger tagger = new MaxentTagger("F:\\stanford-postagger-2014-06-16\\models\\english-bidirectional-distsim.tagger");
File file = new File("F:\\genia_train_data");
File fi[] = file.listFiles();
String name;
int m;
FileWriter fw = null;
BufferedWriter bw = null;
File fil = null;
for(int i =0; i < fi.length; i++){
name = fi[i].getName();
m = name.lastIndexOf(".");
if(name.substring(m+1).equals("txt")){
fil = new File("F:\\test\\" + fi[i].getName());
fw = new FileWriter(fil);
bw = new BufferedWriter(fw);
List<List<HasWord>> sentences = MaxentTagger.tokenizeText(new BufferedReader(new FileReader("F:\\genia_train_data\\" + name)));
for (List<HasWord> sentence : sentences) {
List<TaggedWord> tSentence = tagger.tagSentence(sentence);
bw.write(Sentence.listToString(tSentence, false));
bw.flush();
}
}
}
bw.close();
fw.close();
}
}
今天这个小小程序仅仅调试就占用了我一天的时间,不可否认是效率太低,不会使用Eclipse的debug调试是一方面,理论基础薄弱就是另一个方面。
反省完毕,回到主题:
错误:在控制台可以打印信息,但是写不进txt文本
原因:没有及时 flush() ,
BufferedWriter是缓冲输入流,意思是调用BufferedWriter的write方法时候。数据是先写入到缓冲区里,并没有直接写入到目的文件里。必须调用BufferedWriter的flush()方法。这个方法会刷新一下该缓冲流,也就是会把数据写入到目的文件里。或者你可以调用BufferedWriter的close()方法,该方法会在关闭该输入流之前先刷新一下该缓冲流。也会把数据写入到目的文件里。
如果没有在里面的for()循环中添加 bw.flush(); 这句话,在if 的时候重新 new BufferedWriter(); 就把原来bw(缓冲区)中的覆盖掉了。于是就不能写进文件字符。
以上程序时调试正确的结果:解决的办法就是在第二个for循环中添加了 flush()方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)