2014-12-08 6 views
0
package healthbuddy; 

/** 
* 
* @author tpzap_000 
*/ 
import java.io.*; 
import com.thoughtworks.xstream.XStream; 
import com.thoughtworks.xstream.io.xml.StaxDriver; 
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy; 
import com.thoughtworks.xstream.persistence.PersistenceStrategy; 
import com.thoughtworks.xstream.persistence.XmlArrayList; 
import java.util.List; 
import java.util.Scanner; 



public class PersistentDataModelCntl implements Serializable{ 

private File theFile = new File("PDM.txt"); 
private XStream xstream = new XStream(new StaxDriver()); 
public static PersistentDataModelCntl thePDMCntl; 
private PersistentDataModel thePDM; 

public PersistentDataModelCntl(){ 
    this.readPDMFile(); 
} 
public static PersistentDataModelCntl getPDMCntl(){ 
    if(thePDMCntl == null){ 
     thePDMCntl = new PersistentDataModelCntl(); 
    } 
    return thePDMCntl; 
} 
public void readPDMFile(){ 
    try 
    { 
     System.out.println("in read file"); 
     StringBuilder fileContents = new StringBuilder(); 
     Scanner in = new Scanner(theFile); 
     String tempXML; 
     boolean test = in.hasNextLine(); 
     System.out.println(test); 
      while(in.hasNextLine()){ 
       fileContents.append(in.nextLine()); 
       System.out.println("reading file contents"); 
      } 
      tempXML = fileContents.toString(); 

      thePDM = (PersistentDataModel)xstream.fromXML(tempXML); 
    } 

    //If the file does not exist, thePDM is instantiated to be a new, empty, PDM file. The file  is then written to disk, and then read from disk 
    // using some recursive stuff. Also creates a test UserList so that I don't get a NullPointerException in the LoginCntl. 
    catch(FileNotFoundException ex){ 
     System.out.println("FileNotFound"); 
     thePDM = new PersistentDataModel(); 
     thePDM.thePDMFoodList = new FoodList(); 
     thePDM.thePDMMealList = new MealList(); 
     thePDM.thePDMDietList = new DietList(); 
     thePDM.thePDMDiet = new Diet(); 
     //Creates new attributes if things are null. 
     this.writePDMFile(); 
     this.readPDMFile(); 
     System.out.println("FileNotFound Exception"); 

    } 
    catch(IOException ex){ 
     System.out.println("IO Exception"); 
     ex.printStackTrace(); 

    } 

} 

//Problem Code is here: 
public void writePDMFile(){ 

    try{ 
     String xml = xstream.toXML(thePDM); 
     PrintWriter writer = new PrintWriter(theFile); 
     System.out.println(xml); 
     writer.println(xml); 

    } 
    catch(Exception ex){ 
     System.out.println("There was a problem writing the file."); 
    } 
} 
public PersistentDataModel getPDM(){ 
    return thePDM; 
} 

}자바의 PrintWriter 쓰기는

이 위 내 코드 파일입니다. 현재 데이터 지속성을 위해 객체 직렬화를 사용하는 응용 프로그램이 있지만 XML로 변환하는 중입니다. Xstream 라이브러리를 사용하여 XML을 만들고 있지만 디스크에 쓰는 데 문제가 있습니다. Xstream은 XML을 String으로 제공하여 PrintWriter를 사용하여 텍스트 파일에 쓰려고 시도합니다. 그러나 텍스트 파일이 비어 있지만 그것에 쓰려고 시도하는 문자열 않습니다. PrintWriter에 대한 필자의 이해는 작성해야하는 파일 이름을 제공하고, 파일에 쓰기를 시도하고 (존재하지 않는 경우 파일을 작성), 문자열의 내용을 파일에 작성해야합니다.

도움을 주시면 감사하겠습니다. 내가 어디로 잘못 가고 있는지 확실하지 않습니다.

+0

이 OutputStream에 직접 쓰기보다는 문자열로 메모리에 XML을 구축 toXML' '의 두 인수 양식을 사용하는 것이 더 효율적이 될 것입니다 별도로 작성하십시오. 물론 스트림을 닫아야합니다. –

+0

XStream을 바이너리 스트림으로 직접 보내면 문자 인코딩에 관련된 모든 문제를 피할 수 있습니다 ('FileWidth'를 사용하는'PrintWriter' 생성자는 플랫폼 기본 인코딩을 사용합니다) 반면에'StaxDriver'는 XML을 작성하여 후속 파서가 UTF- 8). –

답변

0

당신은 코드의 끝 부분에

writer.close() 

를 추가해야합니다. 작성자는 파일이 닫힐 때만 파일에 씁니다.

+0

나는 이것을 finally 블록에서하는 것이 좋습니다. 많은 처리를하고 오류가 발생하더라도 파일을 디스크로 플러시 할 수 있습니다. 웹 앱에서 이런 일이 발생하면 누출을 방지하기 위해 핸들을 닫을 수도 있습니다. – Brad

0

PrintWriter::flush() 또는 PrintWriter::close()으로 전화해야합니다.

-1

나는 바보입니다. 내 PrintWriter에서 close를 호출하지 않았습니다. 당신이 파일을 XML을 쓴 후

+1

이 다른 사람들은 그 전에 당신의 질문에 대답했습니다. 아마 다른 세 가지 대답 중 하나를 받아 들여야합니다. – davidahines

0

봅니다 PrintWriter를 닫습니다