1. 程式人生 > >android檔案寫入和讀取

android檔案寫入和讀取

//讀寫檔案函式呼叫
writeFileData(filename,datas);
String result=readFileData(filename); Toast.makeText(Main2Activity.this,result.getClass().toString(),Toast.LENGTH_SHORT).show();

下面是讀寫程式碼的實現:

//檔案寫入
    public void writeFileData(String filename, String content){
        try {
            FileOutputStream fos 
= this.openFileOutput(filename, MODE_PRIVATE);//獲得FileOutputStream //將要寫入的字串轉換為byte陣列 byte[] bytes = content.getBytes(); fos.write(bytes);//將byte陣列寫入檔案 fos.close();//關閉檔案輸出流 } catch (Exception e) { e.printStackTrace(); } }
//檔案讀取 public String readFileData(String fileName){ String result=""; try{ FileInputStream fis = openFileInput(fileName); //獲取檔案長度 int lenght = fis.available(); byte[] buffer = new byte[lenght]; fis.read(buffer);
//將byte陣列轉換成指定格式的字串 result = new String(buffer, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return result; }