写入内部存储 - 引起:android.system.ErrnoException

时间:2016-08-25 19:07:14

标签: android android-file internal-storage android-internal-storage

我正在尝试将类对象保存到内部存储,因此我不必使用SharedPreferences。但是,找不到我要保存的文件。

public class LoginActivity extends AppCompatActivity implements Serializable {

    final String filename = "userInfo.txt";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final File file = new File(this.getFilesDir(), filename);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void Fblogin(){ //Called when user tries to login with Facebook
        //Off-topic FB code here
        new User(/*args*/){
            @Override
            public void userFinished(User user){

            try{
                FileOutputStream fileOutputStream = openFileOutput(filename, MODE_PRIVATE);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
                objectOutputStream.writeObject(user);
                objectOutputStream.flush();
                objectOutputStream.close();

            } catch (IOException e){e.prinstacktrace();}

            }
        }
    }
}

我是否必须自己手动创建文件并将其放入我的项目文件夹,或者createNewFile()是否为我完成了该文件?

错误:

java.io.FileNotFoundException: userInfo.txt: open failed: ENOENT (No such file or directory)
at com.couponwallet.couponwalletconsumer.MainActivity.onCreate(MainActivity.java:124)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
at libcore.io.IoBridge.open(IoBridge.java:442)

编辑:我以某种方式混淆了我的两个活动,这是我的其他活动有问题。此try catch位于MainActivity中的onCreate

try {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("userInfo.txt"));
        /*Above line is line 124 and causes the error*/
        user = (User) ois.readObject();

        Log.v("MainUser", "try statement");

        if (user == null) {
            Log.v("MainUser", "null");
        } else {
            Log.v("MainUser", user.toString());
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
}

0 个答案:

没有答案