0
我正在研究一個用作卷書的android應用程序,並且創建了StudentStore類,該類可以執行所有加載並將自定義列表保存到該文件。我的問題是該文件不是在SD卡中創建的;我嘗試了一些東西,但似乎沒有任何工作。在Android應用程序中找不到文件
public class StudentStore {
public StudentStore(){
Log.d("TAG", "student store constructor");
}
public SortedDoublyList<Student> loadStudents() throws FileNotFoundException {
// sdCard trajectory
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
// Creates directory from path held by the variable named directory
directory.mkdirs();
File rollBookFile = new File(directory.getAbsolutePath()+"StudentsInfo.txt");
SortedDoublyList<Student> studentList = null;
FileInputStream fileInfoIn = null;
ObjectInputStream studentInfoIn = null;
try {
fileInfoIn = new FileInputStream(rollBookFile);
studentInfoIn = new ObjectInputStream(fileInfoIn);
studentList = (SortedDoublyList<Student>) studentInfoIn.readObject();
studentInfoIn.close();
}
catch (IOException ex) {
FileOutputStream fileInfoOut = new FileOutputStream(rollBookFile);
} catch (ClassNotFoundException ex) {
}
// Empty file
if(studentList == null){
studentList = new SortedDoublyList<Student>();
saveStudents(studentList);
}
return studentList;
}
public void saveStudents(SortedDoublyList<Student> studentList) {
// sdCard trajectory
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
// Creates directory from path held by the variable named directory
directory.mkdirs();
// Constructs file from newly obtained directory pointing towards StudentsInfo.txt
File rollBookFile = new File(directory.getAbsolutePath()+"StudentsInfo.txt");
FileOutputStream fileInfoOut = null;
ObjectOutputStream studentInfoOut = null;
try {
fileInfoOut = new FileOutputStream(rollBookFile);
studentInfoOut = new ObjectOutputStream(fileInfoOut);
studentInfoOut.writeObject(studentList);
studentInfoOut.close();
System.out.println("Object Persisted");
}
catch (IOException ex) {
ex.printStackTrace();
}
}
你加入<使用許可權的android:NAME = 「android.permission.WRITE_EXTERNAL_STORAGE」 – nandeesh
謝謝!那正是我錯過的!沒有意識到我會犯這樣一個簡單的錯誤! –