【发布时间】:2020-11-06 22:22:36
【问题描述】:
我找到了一种写出数据的方法,除了应该写到文件的所有单词中,只有最后一个单词出现在输出文件中。 代码如下:
public static void main(String[] args) throws IOException {
for (String s: args) {
//here it gets the file from the doc name in the command line, goes through it, and adds all
//the words to a vector
incorporteVocab();
}
}
public static void incorporteVocab() {
String filename = "C:\\projectTests\\vocabulary.txt"; //file where to write out the vocabulary
for (String w : commonDocumentWords) {
if (!inStopList(w))
addToVocabulary(w, filename);
}
}
public static void addToVocabulary(String word, String filename) {
Vocabulary.add(word);
toDataFile(word, filename);
}
public static void toDataFile(String word, String filename) {
try {
FileWriter myWriter = new FileWriter(filename);
myWriter.write(word);
myWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
请帮忙, 谢谢!
【问题讨论】:
-
因为对于每个单词,您都会重新打开文件,这会使您覆盖之前的内容。要么打开文件一次,写入所有数据,然后关闭它,要么在每次打开时以附加模式打开写入器。
-
知道了!!非常感谢!!
-
传递文件而不是文件名。