作者不在关闭时将文本写入子目录中的文件

时间:2017-11-08 20:44:16

标签: java file

我有一个非常简单的操作,即将一些文本写入子目录中的文件。通过我看到的所有教程,这应该可行,但文件每次都保持为空。它在不写入子目录时起作用,不会抛出任何异常。

File file = new File("./Decks");

public void saveDeck(Deck deck) {
    File deckFile = new File(file, deck.getName() + ".xml");

    try {
        if(!deckFile.exists()){
            deckFile.createNewFile();
        }


        Writer writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(deckFile.getName()), "utf-8"));
        writer.write(deck.toXml());
        writer.close();

    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    }

}

这是甲板课的样子:

public class Deck {
String name;
String cardLocation;

public Deck(String name, String cardLocation) {
    this.name = name;
    this.cardLocation = cardLocation;
}

public String toXml(){
    StringBuilder builder = new StringBuilder();
    builder.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?> \n");
    builder.append("<deck> \n");
    builder.append("<name> " + this.name + " </name> \n");
    builder.append("<cardLocation> " + this.cardLocation + " </cardLocation> \n");
    builder.append("</deck> \n");
    return builder.toString();
}

public String getName() {
    return name;
}

public String getCardLocation() {
    return cardLocation;
}
}

1 个答案:

答案 0 :(得分:1)

File.getName()返回路径的文件名部分, 没有父目录。

鉴于此:

File file = new File("./Decks");

// ...

File deckFile = new File(file, deck.getName() + ".xml");

deckFile.getName()的结果是deck.getName() + ".xml"。 路径部分丢失了。

因此,修复方法是将deckFile.getName()替换为deckFile

Writer writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(deckFile), "utf-8"));
writer.write(deck.toXml());
writer.close();