将自定义对象保存到SD卡(Android)

时间:2015-05-31 17:05:21

标签: android file object save

我正在探索内部储蓄而不是储存SD卡。目前,我正在尝试在SD卡上保存自定义对象(DummyTwice),如下所示:

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

执行在以下位置停止:

FileOutputStream os = new FileOutputStream(file);

捕捉异常:

FileNotFoundException e

我做错了什么?相关常数:

private final static String PUB_EXT_DIR = /data
private final static String FILE_NAME = /obj.dat 

1 个答案:

答案 0 :(得分:1)

你不应该直接在SD卡上书写,你应该使用

> x <- 1
> y <- 2
> m1(x, y)
[1] 9
> x
[1] 3
> y
[1] 2

而不是

f1 <- function(x, y) { x <- x + y x*x } > x <- 1 > y <- 2 > f1(x, y) [1] 9 > x [1] 1 > y [1] 2

getExternalFilesDir(null) 会在Environment.getExternalStorageDirectory()的sdcard上返回私人路径,例如getExternalFilesDir(null)