一、私有文件夹下的文件存取(/data/data/包名)
//写文件在./data/data/com.tt/files/下面 public voidwriteFileData(String fileName,String message){ try{ FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE); byte [] bytes = message.getBytes(); fout.write(bytes); fout.close(); } catch(Exception e){ e.printStackTrace(); } } //------------------------------------------------------- //读文件在./data/data/com.tt/files/下面 public String readFileData(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; }
二、从resource中的raw文件夹中获取文件并读取数据(资源文件只能读不能写)
public String getFromRaw(String fileName){ String res = ""; try{ InputStream in = getResources().openRawResource(R.raw.test1); int length = in.available(); byte [] buffer = new byte[length]; in.read(buffer); res = EncodingUtils.getString(buffer, "UTF-8"); in.close(); } catch(Exception e){ e.printStackTrace(); } return res ; }
三、从asset中获取文件并读取数据(资源文件只能读不能写)
public String getFromAsset(String fileName){ String res=""; try{ InputStream in = getResources().getAssets().open(fileName); int length = in.available(); byte [] buffer = new byte[length]; in.read(buffer); res = EncodingUtils.getString(buffer, "UTF-8"); } catch(Exception e){ e.printStackTrace(); } return res; }