[英]Saving custom object to sdcard (Android)
I'm exploring saving internally versus saving on the sdcard. 我正在探索内部保存而不是保存在sdcard上。 Currently, I'm trying to save a custom object (DummyTwice) on the sdcard, like so: 目前,我正在尝试将自定义对象(DummyTwice)保存在sdcard上,如下所示:
String root = (Environment.getExternalStorageDirectory().toString());
File dir = new File(root + PUB_EXT_DIR);
dir.mkdirs();
File file = new File(dir,FILE_NAME);
try {
DummyTwice dt = new DummyTwice(textEnter.getText().toString());
FileOutputStream os = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(dt);
oos.close();
os.close();
Toast.makeText(v.getContext(),"Object Saved",Toast.LENGTH_SHORT).show();
Toast.makeText(v.getContext(),file.getAbsolutePath(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Execution stops at: 执行在以下位置停止:
FileOutputStream os = new FileOutputStream(file);
Catching the exception: 捕获异常:
FileNotFoundException e
What am I doing wrong? 我究竟做错了什么? Relevant constants: 相关常数:
private final static String PUB_EXT_DIR = /data
private final static String FILE_NAME = /obj.dat
you shouldn't write directly on the sdcard, and you should use 您不应该直接在sdcard上书写,而应该使用
getExternalFilesDir(null)
instead of 代替
Environment.getExternalStorageDirectory()
getExternalFilesDir(null)
returns a private path on the sdcard for your Activity
, like /sdcard/Android/data/package.your.app
getExternalFilesDir(null)
为您的Activity
返回sdcard上的私有路径,例如/sdcard/Android/data/package.your.app
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.