我有一个简单的方法,它读取文件,根据条件修改一些行,然后将修改后的字符串写回到同一文件。概述如下:

import com.google.common.base.Joiner;
import com.google.common.io.Files;

import static java.nio.charset.Charset.defaultCharset;

static final DIR = ;
String enforceVerbTag(String inputfilename) {
    String predictedTags = Files.toString(new File(DIR, inputfilename),
                                          defaultCharset());
    String[] lines = predictedTags.split("\\r?\\n");
    List<String> modifiedLines = new ArrayList<>();
    for (String line : lines) {
        String[] fields = line.split("\\t");
        if (mycondition)
            fields[1] = "VB";
        String modifiedLine = Joiner.on('\t').join(fields);
        modifiedLines.add(modifiedLine);
    }
    modifiedLines.add("");
    Files.write(Joiner.on('\n').join(modifiedLines),
                new File(DIR, inputfilename),
                defaultCharset());
}


输入文件的最后一行为空,我希望输出文件保留该行。但是,尽管modifiedLines.add("")之后是\n上的联接,但输出文件中没有最后一个空行。据我所知,番石榴的Files#write不做任何修整,那为什么会发生呢?

我知道还有许多其他方法可以写出最后一行。但是我想知道这种方法出了什么问题。

最佳答案

这很简单:加入连接器,您将获得一个不终止'\n'的字符串。

first \n
second \n
third (no \n)


然后添加一个空的String,它只会使最后一行终止:

first \n
second \n
third \n
(nothing) (no \n)


您必须添加另一个""以获得空行。

first \n
second \n
third \n
(nothing) \n
(nothing) (no \n)




您可以使用附加换行符的函数来代替joiner,但这会更长(至少在Java

关于java - Guava 的`Files#write`不写最后一个空行吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25943701/

10-11 02:38