一:Android中檔案讀取更具檔案位置可分為三種:
第一種:從asset讀取資料:
//方法:從asset中擷取檔案並讀取資料 public String getFromAsset(String fileName){ String result=""; try{ InputStream in = getResources().getAssets().open(fileName);//從Assets中的檔案擷取輸入資料流 int length = in.available();//擷取檔案的位元組數 byte [] buffer = new byte[length];//建立byte數組 in.read(buffer);//將檔案中的資料讀取到byte數組中 result = EncodingUtils.getString(buffer, ENCODING);//將byte數群組轉換成指定格式的字串 } catch(IOException e){ e.printStackTrace();//捕獲異常並列印 } catch(Exception e){ e.printStackTrace(); } return result; }
第二種:從resource中的raw檔案夾中讀取資料:
//方法:從resource中的raw檔案夾中擷取檔案並讀取資料 public String getFromRaw(String fileName){ String result = ""; try{ InputStream in = getResources().openRawResource(R.raw.test1);//從Resources中raw中的檔案擷取輸入資料流 int length = in.available();//擷取檔案的位元組數 byte [] buffer = new byte[length];//建立byte數組 in.read(buffer);//將檔案中的資料讀取到byte數組中 result = EncodingUtils.getString(buffer, ENCODING);//將byte數群組轉換成指定格式的字串 in.close();//關閉輸入資料流 } catch(IOException e){ e.printStackTrace();//捕獲異常並列印 } catch(Exception e){ e.printStackTrace(); } return result; }
第三種:從系統檔案或sd卡讀取資料:
//方法:開啟指定檔案,讀取其資料,返回字串對象 public String readFileData(String fileName){ String result=""; try{ FileInputStream fin = openFileInput(fileName);//獲得FileInputStream對象 int length = fin.available();//擷取檔案長度 byte [] buffer = new byte[length];//建立byte數組用於讀入資料 fin.read(buffer);//將檔案內容讀入到byte數組中 result = EncodingUtils.getString(buffer, ENCODING);//將byte數群組轉換成指定格式的字串 fin.close();//關閉檔案輸入資料流 } catch(Exception e){ e.printStackTrace();//捕獲異常並列印 } return result;//返回讀到的資料字串 } }
二:相對於讀取資料寫入檔案就少了檔案寫入只能寫入系統檔案,sd卡檔案上
兩者方法通用:
void writeData(String filename,String msg){ try {FileOutputStream fos=this.openFileOutput(filename, MODE_PRIVATE);byte[] buf=msg.getBytes();fos.write(buf);fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} }
ok,就這些了!