Java Spring boot应用程序:向现有txt文件追加字符串

Java Spring boot应用程序:向现有txt文件追加字符串,java,spring,spring-boot,Java,Spring,Spring Boot,我想在spring boot应用程序中向现有的file.txt文件追加一个字符串。 我的文件位于参考资料下(src/main/resources/file.txt) 我已经用org.apache.commons.io.FileUtils尝试过这个 public static boolean addWord(String word) { if(!wordExist(word, getFileName())) { File file = new File(g

我想在spring boot应用程序中向现有的file.txt文件追加一个字符串。 我的文件位于参考资料下(src/main/resources/file.txt)

我已经用org.apache.commons.io.FileUtils尝试过这个

public static boolean addWord(String word) {

        if(!wordExist(word, getFileName())) {
            File file = new File(getFileName());
            try {
                Set<String> words = new HashSet<>(readLines(new File(getFileName())));
                words.add(word);
                FileUtils.writeLines(file,words);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
}
公共静态布尔添加字(字符串字){
如果(!wordExist(word,getFileName())){
File File=新文件(getFileName());
试一试{
Set words=newhashset(readLines(新文件(getFileName()));
添加(word);
FileUtils.writeLines(文件,字);
返回true;
}捕获(IOE异常){
e、 printStackTrace();
}
}
返回false;
}

这很好,但是当我重新启动服务器时,文件会回滚。似乎字符串不会永久添加到file.txt中。有什么想法吗?感谢方法writeLines关闭其FileOutputStream,并且文件类没有close methodwait,是否要追加?因为这里是覆盖——写(File File,CharSequence data,boolean append)我猜是在开始的某个地方覆盖了文件。实际上,我将文件中的所有字符串读取到一个集合中,然后将我的新字符串添加到该集合中,然后用集合覆盖现有文件。这是因为我将它放在src/main/resources下