在Android应用程序中找不到文件

时间:2014-04-12 07:38:00

标签: android file file-not-found

我正在开发一个用作滚动书的Android应用程序,我创建了StudentStore类,它可以将所有加载和保存自定义列表保存到文件中。我的问题是该文件不是在sdCard中创建的;我尝试过一些东西,但似乎都没有。

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(); 
        } 
    } 

1 个答案:

答案 0 :(得分:0)

在编写数据之前,尝试添加createNewFile()方法来创建文件:

try { 
    rollBookFile.createNewFile();

    fileInfoOut = new FileOutputStream(rollBookFile); 
    studentInfoOut = new ObjectOutputStream(fileInfoOut);
    studentInfoOut.writeObject(studentList); 
    studentInfoOut.close(); 
    System.out.println("Object Persisted"); 
}