Java将数据写入外部文件

Java将数据写入外部文件,java,file-io,Java,File Io,我找到了一种写数据的方法,除了应该写到文件中的所有单词,只有最后一个单词出现在输出文件中。 代码如下: 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 al

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

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();
    }
} 
请帮忙,
谢谢大家!

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

FileWriter myWriter = new FileWriter(filename, true);

因为对于每个单词,你都会重新打开文件,这会使你覆盖以前的内容。要么打开文件一次,写入所有数据,然后关闭它,要么在每次打开时以追加模式打开写入程序。明白了!!非常感谢你!!传递文件而不是文件名。