android基礎入門資料存放區之File(13)

來源:互聯網
上載者:User

一.資料存放區之File:

android中可以在裝置本身的存放裝置或者外接的存放裝置中建立用於儲存資料的檔案。在預設的狀態下,檔案是不能在不同的程式間共用的。

在android中的內容物件(Context)提供了檔案操作的幾個方法。

1).openFileOutput(檔案名稱,操作模式)。

2).openFileInput(檔案名稱,操作模式)。

第一個參數用於指定檔案名稱,不能包含路徑分隔字元 "/ ",如果檔案不存在,android會自動的建立它,建立的檔案儲存在data/data//files/目錄下,這裡想查看檔案路徑是需要在File Explorer中查看,這就要在 Window -> Show View -> Other -> Android -> File Explorer.

這裡說到的操作模式有四種:

1).Context.MODE_PRIVATE = 0

此種為預設操作模式,代表該檔案是私人資料,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原檔案的內容,如果想把新寫入的追加到原檔案可以使用Context.MODE_APPEND。

2).Context.MODE_WORLD_READABLE = 1

此種模式表示當前檔案可被其他應用讀取。

3).Context.MODE_WORLD_WRITEABLE = 2

此種模式表示當前檔案可被其他應用寫入。

4).Context.MODE_APPEND = 32768

此種模式會檢查檔案是否存在,存在就往檔案中追加內容,如果不存在則建立檔案,新增內容。

注意:如果想被其他應用可讀可寫需要openFileOutput(檔案名稱,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE )。


執行個體示範:

布局檔案:

                                    


服務類(FileService.java):

public class FileService {  private Context context;public FileService(Context context) {this.context = context;}public void fileOutput(String fileName,String fileContext) throws Exception{FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);fos.write(fileContext.getBytes());fos.close();}public String fileIntput(String fileName) throws Exception{    byte[] data = null;System.out.println(fileName);FileInputStream fis = context.openFileInput(fileName);//讀取緩衝區資料ByteArrayOutputStream  baos = new ByteArrayOutputStream();byte[] b = new byte[1024];int len = 0;    while(-1 != (len = fis.read(b))){       baos.write(b,0,len);}     data = baos.toByteArray();return new String(data);}public void saveToSDCard(String fileName,String fileContext) throws Exception{   File file = new File(Environment.getExternalStorageDirectory(),fileName);   //不能在使用api提供的openFileInput()方法,因為此方法是將檔案存放在手機內建的儲存位置。   FileOutputStream  out = new FileOutputStream(file);      out.write(fileContext.getBytes());      out.close();}}

主介面(FlieMain.java):

public class FlieMain extends Activity {private Button b1;private Button b2;private EditText e1 ;private EditText e2;private TextView t1;    private Button b3;    private FileService files;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_flie_main);b1 = (Button)findViewById(R.id.button1);b2 = (Button)findViewById(R.id.button2);b3 = (Button)findViewById(R.id.button3);files = new FileService(this);b1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {e1 = (EditText)findViewById(R.id.editText1);e2 = (EditText)findViewById(R.id.editText2);String fileName = e1.getText().toString();String fileCon = e2.getText().toString();try {files.fileOutput(fileName, fileCon);toastPrint("儲存成功");} catch (Exception e) {toastPrint("儲存失敗");e.printStackTrace();}}});b3.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stube1 = (EditText)findViewById(R.id.editText1);e2 = (EditText)findViewById(R.id.editText2);String fileName = e1.getText().toString();String fileCon = e2.getText().toString();try {//判斷sd卡是否可以讀寫,是否存在sd卡。if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){files.saveToSDCard(fileName, fileCon);toastPrint("儲存成功");}else{toastPrint("儲存失敗");}} catch (Exception e) {toastPrint("儲存失敗");e.printStackTrace();}}});}public void toastPrint(String str){Toast.makeText(this, str, Toast.LENGTH_SHORT).show();}public void onClick(View v) {try {String str = files.fileIntput(e1.getText().toString());toastPrint("讀取成功"+str);} catch (Exception e) {// TODO Auto-generated catch blocktoastPrint("讀取失敗");e.printStackTrace();} }@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.flie_main, menu);return true;}}

當我們想手機SD卡存入資料時,必須在AndroidManifest.xml中添加許可權:

在SD卡中建立與刪除檔案操作

往SD卡中寫入資料許可權


運行效果:

在第一個輸入框中輸入檔案名稱,然後在下面的輸入框輸入檔案內容。點擊儲存。

查看檔案位置:

點擊讀取按鈕時:

當我們點擊存入SD卡時:




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.