在Android中根據檔案位置的不同,可分為四種檔案讀取方式,具體如下;
//方法:從resource中的raw檔案夾中擷取檔案並讀取資料,注意:只能讀取不能寫入資料
public String getFromRaw(int fileId) { InputStream in = null; String result = ""; ByteArrayOutputStream baos=null; try { // 擷取Resources資源檔流 in = getResources().openRawResource(fileId); // 檔案大小 int length = in.available(); // 建立byte數組 byte[] buf = new byte[length]; // 建立記憶體流加快效率 baos = new ByteArrayOutputStream(); int count = 0; while ((count = in.read(buf)) != -1) { baos.write(buf, 0, count); } result=new String(baos.toByteArray(), "UTF-8"); //result = EncodingUtils.getString(buf, "UTF-8"); } catch (IOException e) { Toast.makeText(this, "找不到檔案", 2000).show(); } finally{ if(baos!=null) try { baos.close(); } catch (IOException e) { e.printStackTrace(); } if(in!=null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
//方法:從asset中擷取檔案並讀取資料,只能讀取不能寫入資料
public String getFromAsset(String fileName){//fileName="read_asset.txt" InputStream in = null; String result = ""; ByteArrayOutputStream baos=null; try{ in = getAssets().open(fileName); int size = in.available(); byte[] buffer = new byte[size]; baos = new ByteArrayOutputStream(); while(in.read(buffer)!=-1){ baos.write(buffer); } // Convert the buffer into a string. // result = new String(baos.toByteArray(),"UTF-8"); result = EncodingUtils.getString(baos.toByteArray(), "UTF-8"); }catch(IOException e){ Toast.makeText(this, "找不到檔案", 2000).show(); } finally{ if(baos!=null) try { baos.close(); } catch (IOException e) { e.printStackTrace(); } if(in!=null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
//方法:向指定系統檔案中寫入指定的資料
public void writeFileData(String fileName, String message) {FileOutputStream fos = null;try {fos = openFileOutput(fileName, Context.MODE_PRIVATE);byte[] bytes = message.getBytes();fos.write(bytes);fos.flush();} catch (IOException e) {Toast.makeText(this, "檔案寫入錯誤", 2000).show();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}
//方法:開啟指定系統檔案讀取其資料,
public String readFileData(String fileName){ FileInputStream fis=null; String result=""; try{ fis = openFileInput(fileName); int size = fis.available(); byte [] buffer = new byte[size]; fis.read(buffer); result=new String(buffer,"UTF-8"); }catch(IOException e){ Toast.makeText(this, "檔案沒有找到", 2000).show(); }finally{ if(fis!=null){ try {fis.close();} catch (IOException e) {e.printStackTrace();} } } return result;//返回讀到的資料字串 }
ok,下寫到這裡,待續