簡體   English   中英

編寫器在關閉時未將文本寫入子目錄中的文件

[英]Writer not writing text to file in subdirectory on close

我有一個非常簡單的操作,可以將一些文本寫入子目錄中的文件。 我看過的所有教程都可以,但是每次文件都為空。 當不寫入子目錄時,它將起作用,不會引發任何異常。

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

}

這是deck類的樣子:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM