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;
}
이 위 내 코드 파일입니다. 현재 데이터 지속성을 위해 객체 직렬화를 사용하는 응용 프로그램이 있지만 XML로 변환하는 중입니다. Xstream 라이브러리를 사용하여 XML을 만들고 있지만 디스크에 쓰는 데 문제가 있습니다. Xstream은 XML을 String으로 제공하여 PrintWriter를 사용하여 텍스트 파일에 쓰려고 시도합니다. 그러나 텍스트 파일이 비어 있지만 그것에 쓰려고 시도하는 문자열 않습니다. PrintWriter에 대한 필자의 이해는 작성해야하는 파일 이름을 제공하고, 파일에 쓰기를 시도하고 (존재하지 않는 경우 파일을 작성), 문자열의 내용을 파일에 작성해야합니다.
도움을 주시면 감사하겠습니다. 내가 어디로 잘못 가고 있는지 확실하지 않습니다.
이 OutputStream에 직접 쓰기보다는 문자열로 메모리에 XML을 구축 toXML' '의 두 인수 양식을 사용하는 것이 더 효율적이 될 것입니다 별도로 작성하십시오. 물론 스트림을 닫아야합니다. –
XStream을 바이너리 스트림으로 직접 보내면 문자 인코딩에 관련된 모든 문제를 피할 수 있습니다 ('FileWidth'를 사용하는'PrintWriter' 생성자는 플랫폼 기본 인코딩을 사용합니다) 반면에'StaxDriver'는 XML을 작성하여 후속 파서가 UTF- 8). –