Android編程中FileOutputStream與openFileOutput()的區別分析_Android

來源:互聯網
上載者:User

本文執行個體分析了Android編程中FileOutputStream與openFileOutput()的區別。分享給大家供大家參考,具體如下:

openFileOutput()

首先給大家介紹使用檔案如何對資料進行儲存,Activity提供了openFileOutput()方法可以用於把資料輸出到檔案中,具體的實現過程與在J2SE環境中儲存資料到檔案中是一樣的。

public void save(){    try {      FileOutputStream outStream=this.openFileOutput("a.txt",Context.MODE_WORLD_READABLE);      outStream.write(text.getText().toString().getBytes());      outStream.close();      Toast.makeText(MyActivity.this,"Saved",Toast.LENGTH_LONG).show();    } catch (FileNotFoundException e) {      return;    }    catch (IOException e){      return ;    }}

openFileOutput()方法的第一參數用於指定檔案名稱,不能包含路徑分隔字元"/" ,如果檔案不存在,Android 會自動建立它。建立的檔案儲存在/data/data/<package name>/files目錄,如: /data/data/cn.itcast.action/files/itcast.txt ,通過點擊Eclipse菜單"Window"-"Show View"-"Other",在交談視窗中展開android檔案夾,選擇下面的File Explorer視圖,然後在File Explorer視圖中展開/data/data/<package name>/files目錄就可以看到該檔案。

openFileOutput()方法的第二參數用於指定操作模式,有四種模式,分別為: Context.MODE_PRIVATE    =  0
Context.MODE_APPEND    =  32768
Context.MODE_WORLD_READABLE =  1
Context.MODE_WORLD_WRITEABLE =  2
Context.MODE_PRIVATE:為預設操作模式,代表該檔案是私人資料,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原檔案的內容,如果想把新寫入的內容追加到原檔案中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式會檢查檔案是否存在,存在就往檔案追加內容,否則就建立新檔案。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有許可權讀寫該檔案。
MODE_WORLD_READABLE:表示當前檔案可以被其他應用讀取;MODE_WORLD_WRITEABLE:表示當前檔案可以被其他應用寫入。
如果希望檔案被其他應用讀和寫,可以傳入:

複製代碼 代碼如下:
openFileOutput("itcast.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

android有一套自己的安全模型,當應用程式(.apk)在安裝時系統就會分配給他一個userid,當該應用要去訪問其他資源比如檔案的時候,就需要userid匹配。預設情況下,任何應用建立的檔案,sharedpreferences,資料庫都應該是私人的(位於/data/data/<package name>/files),其他程式無法訪問。除非在建立時指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE ,只有這樣其他程式才能正確訪問。

讀取檔案內容

public void load(){  try {    FileInputStream inStream=this.openFileInput("a.txt");    ByteArrayOutputStream stream=new ByteArrayOutputStream();    byte[] buffer=new byte[1024];    int length=-1;    while((length=inStream.read(buffer))!=-1)  {      stream.write(buffer,0,length);    }    stream.close();    inStream.close();    text.setText(stream.toString());    Toast.makeText(MyActivity.this,"Loaded",Toast.LENGTH_LONG).show();  } catch (FileNotFoundException e) {    e.printStackTrace();  }  catch (IOException e){    return ;  }}

對於私人檔案只能被建立該檔案的應用訪問,如果希望檔案能被其他應用讀和寫,可以在建立檔案時,指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE許可權。

Activity還提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用於擷取/data/data/<package name>/cache目錄
getFilesDir()方法用於擷取/data/data/<package name>/files目錄

把檔案放入SD卡

使用Activity的openFileOutput()方法儲存檔案,檔案是存放在手機空間上,一般手機的儲存空間不是很大,存放些小檔案還行,如果要存放像視頻這樣的大檔案,是不可行的。對於像視頻這樣的大檔案,我們可以把它存放在SDCard。 SDCard是幹什麼的?你可以把它看作是移動硬碟或隨身碟。

在模擬器中使用SDCard,你需要先建立一張SDCard卡(當然不是真的SDCard,只是鏡像檔案)。建立SDCard可以在Eclipse建立模擬器時隨同建立,也可以使用DOS命令進行建立,如下:

在Dos視窗中進入android SDK安裝路徑的tools目錄,輸入以下命令建立一張容量為2G的SDCard,檔案尾碼可以隨便取,建議使用.img:

mksdcard 2048M D:\AndroidTool\sdcard.img

在程式中訪問SDCard,你需要申請訪問SDCard的許可權。

在AndroidManifest.xml中加入訪問SDCard的許可權如下:

<!– 在SDCard中建立與刪除檔案許可權 –><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><!– 往SDCard寫入資料許可權 –><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

要往SDCard存放檔案,程式必須先判斷手機是否裝有SDCard,並且可以進行讀寫。

注意:訪問SDCard必須在AndroidManifest.xml中加入訪問SDCard的許可權

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){   File sdCardDir = Environment.getExternalStorageDirectory();//擷取SDCard目錄   File saveFile = new File(sdCardDir, "a.txt");   FileOutputStream outStream = new FileOutputStream(saveFile);   outStream.write("test".getBytes());   outStream.close();}

Environment.getExternalStorageState()方法用於擷取SDCard的狀態,如果手機裝有SDCard,並且可以進行讀寫,那麼方法返回的狀態等於Environment.MEDIA_MOUNTED。

Environment.getExternalStorageDirectory()方法用於擷取SDCard的目錄,當然要擷取SDCard的目錄,你也可以這樣寫:

File sdCardDir = new File("/sdcard"); //擷取SDCard目錄File saveFile = new File(sdCardDir, "itcast.txt"); //上面兩句代碼可以合成一句: File saveFile = new File("/sdcard/a.txt");FileOutputStream outStream = new FileOutputStream(saveFile);outStream.write("test".getBytes());outStream.close();

最後附上一個使用openFileOutput的例子存取對象:

public class MainActivity extends Activity {  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);  }  public void button(View view){    Person p = new Person();    p.setAge(10);    p.setName("Lee");    saveObject(p, "MainActivity.dat");  }  public void button2(View view){    Person p = (Person) readObject("MainActivity.dat");    System.out.println(p.getAge());  }  public boolean saveObject(Serializable ser, String file) {    FileOutputStream fos = null;    ObjectOutputStream oos = null;    try{      fos = openFileOutput(file, MODE_PRIVATE);      oos = new ObjectOutputStream(fos);      oos.writeObject(ser);      oos.flush();      return true;    }catch(Exception e){      e.printStackTrace();      return false;    }finally{      try {        oos.close();      } catch (Exception e) {}      try {        fos.close();      } catch (Exception e) {}    }  }  /**   * 讀取對象   * @param file   * @return   * @throws IOException   */  public Serializable readObject(String file){    FileInputStream fis = null;    ObjectInputStream ois = null;    try{      fis = openFileInput(file);      ois = new ObjectInputStream(fis);      return (Serializable)ois.readObject();    }catch(FileNotFoundException e){    }catch(Exception e){      e.printStackTrace();      //還原序列化失敗 - 刪除快取檔案      if(e instanceof InvalidClassException){        File data = getFileStreamPath(file);        data.delete();      }    }finally{      try {        ois.close();      } catch (Exception e) {}      try {        fis.close();      } catch (Exception e) {}    }    return null;  }}class Person implements Serializable{  int age;  String name;  public int getAge() {    return age;  }  public void setAge(int age) {    this.age = age;  }  public String getName() {    return name;  }  public void setName(String name) {    this.name = name;  }}

更多關於Android相關內容感興趣的讀者可查看本站專題:《Android開發入門與進階教程》、《Android資料庫操作技巧總結》及《Android控制項用法總結》

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.