首页 > 解决方案 > Java 将数据写入外部文件

问题描述

我找到了一种写出数据的方法,除了应该写到文件的所有单词中,只有最后一个单词出现在输出文件中。这是代码:

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();
    }
} 

请帮忙,谢谢!

标签: javafile-io

解决方案


您可以将 FileWriter 的第二个参数更改为true以使其将新数据附加到文件中:

FileWriter myWriter = new FileWriter(filename, true);

推荐阅读