2013-09-05 6 views
0

Java로 파일을 읽고 쓰는 방법에 어려움을 겪고 있습니다.파일 읽기 및 쓰기

protected Object readData(String filename) { 
    Object result; 
    FileInputStream fis; 
    ObjectInputStream ois; 
    try { 
     fis = openFileInput(filename); 
     ois = new ObjectInputStream(fis); 
     result = ois.readObject(); 
     ois.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     System.err.println(filename + " not found"); 
     return null; 
    } catch (StreamCorruptedException e) { 
     e.printStackTrace(); 
     System.err.println(filename + " input stream corrupted"); 
     return null; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     System.err.println("I/O error in reading " + filename); 
     return null; 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
     return null; 
    } 
    return result; 
} 

그리고 쓰기 방법 :

protected Object writeData(String filename, Object data) { 
    FileOutputStream fos; 
    ObjectOutputStream oos; 
    try { 
     fos = openFileOutput(filename, Context.MODE_PRIVATE); 
     oos = new ObjectOutputStream(fos); 
     oos.writeObject(data); 
     oos.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     System.err.println(filename + " not found"); 
    } catch (StreamCorruptedException e) { 
     e.printStackTrace(); 
     System.err.println(filename + " output stream corrupted"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     System.err.println("I/O error in writing " + filename); 
    } 
    return null; 
} 

public class EconAppData implements Serializable { 

private static final long serialVersionUID = 1432933606399916716L; 
protected transient ArrayList<Favorite> favorites; 
protected transient List<CatalogTitle> catalogLists; 
protected transient int rangeMonthlySettings; 
protected transient int rangeQuarterlySettings; 
protected transient int rangeAnnualSettings; 

EconAppData() { 
    favorites = new ArrayList<Favorite>(); 
    catalogLists = new ArrayList<CatalogTitle>(); 
    rangeMonthlySettings = 3; 
    rangeQuarterlySettings = 5; 
    rangeAnnualSettings = -1; 
} 
} 

이 내 읽기 방법 :

나는 파일에 기록됩니다 다음과 같은 클래스가 문제 : 내 코드를 디버깅 할 때 나타나는 것처럼 보입니다. 예외없이 파일을 읽고 쓸 수 있습니다 (파일이 존재하는 한). 내 데이터를 읽고 EconAppData가 null이 아니라는 것을 알았지 만, ArrayLists는 null이고 int는 0입니다.이 값을 계산하고 파일에 기록합니다. 그런 다음 파일을 다시 읽고 (디버깅 목적으로) 계산 한 모든 데이터가 사라 졌음을 확인합니다. 다시 EconAppData는 null이 아니지만 arraylists는 null이고 int는 0입니다.

질문 : : 개체를 파일에 포함하는 클래스를 올바르게 읽고 쓰려면 어떻게해야합니까?

미리 감사드립니다.

+0

? 코드를 게시 할 수 있습니까? –

답변

5

변수는 모두 일시적이므로 저장 /로드되지 않습니다. 모든 변수에서 일시적인 속성을 제거하십시오.

은 참조 :`openFileInput` 무엇을하지

Why does Java have transient fields?

+0

감사합니다. 그것은 완벽하게 작동했습니다. – buczek