Android 讀寫檔案操作程式

來源:互聯網
上載者:User
 代碼如下 複製代碼

資料存放區與訪問常用方式:
檔案
SharedPreferences(偏好參數設定)
SQLite資料庫
內容提供者(Content provider)
網路

Activity(Context)
Context.getCacheDir()方法用於擷取/data/data/<package name>/cache目錄
Context.getFilesDir()方法用於擷取/data/data/<package name>/files目錄

Activity(Context)提供了openFileOutput(filename,mode)方法用於把資料輸出到檔案中;
第一個參數用於指定檔案名稱,不能包含路徑分隔字元‘/'
第二個參數為操作模式:
Context.MODE_PRIVATE:私人操作模式建立出來的檔案只能被本程式訪問,如果檔案不存在,會自動建立,另外:寫入檔案中的內容會覆蓋原檔案的內容;
Context.MODE_APPEND:模式會檢查檔案是否存在,如果存在則會追加內容,否則建立新檔案;
Context.MODE_READABLE:表示當前檔案可以被其它應用讀取;
Context.MODE_WRITEABLE:表示當前檔案可以被其它應用寫入;

如果希望檔案被其它應用讀和寫:傳入(Context.MODE_READABLE+Context.MODE_WRITEABLE)
FileOutputStream outStream = context.openFileOutput(filename,Context.MODE_PRIVATE);

例子

//寫資料
public void writeFile(String fileName,String writestr{
  try{

        FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);

        byte [] bytes = writestr.getBytes();

        fout.write(bytes);

        fout.close();
      }

        catch(Exception e){
        e.printStackTrace();
       }
}

//讀資料
public String readFile(String fileName){
  String res="";
  try{
         FileInputStream fin = openFileInput(fileName);
         int length = fin.available();
         byte [] buffer = new byte[length];
         fin.read(buffer);    
         res = EncodingUtils.getString(buffer, "UTF-8");
         fin.close();    
     }
     catch(Exception e){
         e.printStackTrace();
     }
     return res;

}  

//param 檔案名稱,操作方式

android有一套自己的安全模型,當應用程式(.apk)在安裝時系統會分配給一個userid,當該應用去訪問其它資源如檔案的時候,會進行 userid的匹配,預設情況下任何應用建立的檔案,sharedpreferences,資料庫都是私人的(建立的檔案儲存在/data/data /<package name>/files目錄下),只有指定操作模式為外部可讀或寫才可以被其它程式訪問;

讀取檔案:

<1>
FileInputStream inStream = context.openFileInput(filename);
Log.i(TAG,inStream....)

<2>
path="/data/data/<package name>/files/hello.txt";
File file = new File(path);
FileInputStream inStream = new FileInputStream(file);
Log.i(TAG,inStream....)

ctrl + shift + x/y 大小寫

從resource的raw中讀取檔案資料:

String res = "";
try{
 
    //得到資源中的Raw資料流
    InputStream in = getResources().openRawResource(R.raw.test);

    //得到資料的大小
    int length = in.available();      

    byte [] buffer = new byte[length];       

    //讀取資料
    in.read(buffer);        

    //依test.txt的編碼類別型選擇合適的編碼,如果不調整會亂碼
    res = EncodingUtils.getString(buffer, "BIG5");
   
    //關閉   
    in.close();           

   }catch(Exception e){
      e.printStackTrace();        
   }

現在我來給大家總結一個執行個體

 代碼如下 複製代碼

/**
 * 【檔案操作】
 */
package Iwit.IwitTest;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;
import android.widget.Toast;

/**
 * @author Shine
 *【檔案讀,寫】
 */
public class FileOperate

 /**
  * 【讀取檔案】
  * @param context
  * @param fileName
  * @return
  */
 public String ReadText(Context context,String fileName)
 {
       FileInputStream fIn = null;
       InputStreamReader isr = null;      
       char[] inputBuffer = new char[255];
       String data = null;      
       try
       {
        fIn =context.openFileInput(fileName);     
           isr = new InputStreamReader(fIn);
           isr.read(inputBuffer);
           data = new String(inputBuffer);
           Toast.makeText(context, "read Succeed",Toast.LENGTH_SHORT).show();
       }
      catch (Exception e)
          {     
       e.printStackTrace();
       Toast.makeText(context, " not read",Toast.LENGTH_SHORT).show();
          }
       finally
       {
              try {
                     isr.close();
                     fIn.close();
                   }
              catch (IOException e)
              {
                    e.printStackTrace();
              }
           }
       return data;
   }
 
 /**
  * 【寫入檔案】
  * @param context
  * @param fileName
  * @param data
  */
 public void WriteText(Context context, String fileName,String data)
 {
       FileOutputStream fOut = null;
       OutputStreamWriter osw = null;
      
       try{
        fOut =context.openFileOutput(fileName, 1);
           osw = new OutputStreamWriter(fOut);
           osw.write(data);
           osw.flush();
           Toast.makeText(context, " saved",Toast.LENGTH_SHORT).show();
           }
           catch (Exception e)
           {     
           e.printStackTrace();
           Toast.makeText(context, " not saved",Toast.LENGTH_SHORT).show();
           }
           finally
           {
              try {
                     osw.close();
                     fOut.close();
                   }
              catch (IOException e)
               {
                    e.printStackTrace();
                 }
           }
  }
}

上面就可以實現對檔案的讀寫操作了

聯繫我們

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