2017-11-08 1 views
0

하위 디렉토리의 파일에 텍스트를 작성하는 작업이 매우 간단합니다. 필자가 보았던 모든 자습서에서이 작업은 효과가 있지만 파일은 매번 비어 있습니다. 하위 디렉토리에 쓰지 않을 때 작동하며 예외가 발생하지 않습니다.작성자가 닫을 때 하위 디렉토리의 파일에 텍스트를 쓰지 않습니다.

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

당신이 그것을 디버깅을 시도 해 봤나 :

그래서 수정은 단순히 deckFiledeckFile.getName()를 대체하는 것입니다? 갑판에 무엇을 가지고 있습니까? –

답변

1

File.getName()이 경로, 상위 디렉토리가없는 의 파일 이름 부분을 반환

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

} 

는 다음과 같이 갑판 클래스는 모습입니다.

을 감안할 때이 :

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

// ... 

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

deckFile.getName()의 결과는 deck.getName() + ".xml"입니다. 경로 부분이 손실됩니다.

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

죄송합니다, 내가 deck.getName() 그냥 문자열을 반환하는 질문에 어떻게 불분명했다. 파일에 대한 생성자를 올바르게 따르는 경우 File (file, fileName)은 ./Decks/fileName을 수행하는 것과 동일합니다. –

+0

@EricH 내 메시지가 더 명확해질 수 있습니다. 문제는'new FileOutputStream (deckFile.getName())'입니다. 이것은'deckFile'에서 경로 부분을 제거합니다. 그것은'new FileOutputStream (deckFile)'이어야합니다. – janos

관련 문제