2015-05-31 33 views
0

我正在探索在內部保存還是在SD卡上保存。目前,我試圖在SD卡保存自定義對象(DummyTwice),像這樣:將自定義對象保存到SD卡(Android)

  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

你不應該在SD卡直接寫,你應該使用,而不是

getExternalFilesDir(null) 

Environment.getExternalStorageDirectory()

getExternalFilesDir(null)在SD卡返回的私人路徑爲您的Activity,如/sdcard/Android/data/package.your.app

+0

謝謝!那會是私人還是公共? – user2892437

+0

私人爲您的應用程序。 – Blackbelt