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입니다.
질문 : : 개체를 파일에 포함하는 클래스를 올바르게 읽고 쓰려면 어떻게해야합니까?
미리 감사드립니다.
? 코드를 게시 할 수 있습니까? –