Android有一套本身的安全模型, 可参见Android开发文档。当应用程序安装时就会分配一个userid,当应用要去访问其余资源好比文件时,须要userid匹配。默认状况下 ,任何应用建立的文件,数据库, sharedpreferences都应该是私有的(位于/data/data/your_project/files/),其他程序没法访问。除非在建立时指明是MODE_WORLD_READABLE 或者 MODE_WORLD_WRITEABLE,只要这样其他程序才能正确访问。由于有这种Android读写文件的方法在安全上有所保障,进程打开文件时Android要求检查进程的user id。因此不能直接用java的api来打开,由于java的io函数没有提这个机制 。有一个问题系统必须已经root,而且文件浏览器取得root权限不然经过文件浏览器是看不到那些目录的。java
1、私有文件夹下的文件存取(./data/data/com.包名/files/下面,至关于程序工做目录)linux
没法用java的api直接打开程序私有的数据 ,默认路径为/data/data/your_project/files/,从sdcard中去读文件,首先要把文件经过\android-sdk-windows\tools\adb.exe把本地计算机上的文件copy到sdcard上去,adb.exe push e:/Android.txt/sdcard/, 不能够用adb.exe push e:\Android.txt \sdcard\,注意斜杠的,在linux下和winodws下是不同的, 一样: 把仿真器上的文件copy到本地计算机上用: adb pull ./sdcard/Android.txt e:/ ,读取路径能够用“/sdcard/Android.txt”也能够用“mnt/sdcard/Android.txt”
android
如:数据库
FileReader file = new FileReader("Android.txt");
这里特别强调私有数据!言外之意是若是某个文件或者数据不是程序私有的,既访问它时无须通过Android的权限检查,那么仍是能够用java的io api来直接访问的。所谓的非私有数据是只放在sdcard上的文件或者数据,apache
能够用java的io api来直接打开sdcard上文件。windows
如:
api
FileReader file = new FileReader("/sdcard/Android.txt");
若是要打开程序本身私有的文件和数据,那必须使用Activity提供openFileOutput和openFileInput方法。建立程序私有的文件,因为权限方面的要求,必须使用activity提供的Android读写文件方法。浏览器
如:import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.http.util.EncodingUtils; public void writeFileData(String fileName,String message){ try{ FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE); //OutputStreamWriter outWriter = new OutputStreamWriter(fout); byte [] bytes = message.getBytes(); fout.write(bytes); fout.close(); } catch(Exception e){ e.printStackTrace(); } } public String readFileData(String fileName){ String res=""; try{ //FileInputStream fin = openFileInput(fileName); //InputStreamReader inReader = new InputStreamReader(fin); //或者 FileInputStream fin = new FileInputStream(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; }2、从resource中的raw文件夹中获取文件并读取数据(资源文件只能读不能写,在"\程序名\res\raw\FileName.txt")
public String getFromRaw(String fileName){ String res = ""; try{ InputStream in = getResources().openRawResource(R.raw.test1); //资源在\Test\res\raw\test1.txt int length = in.available(); byte [] buffer = new byte[length]; in.read(buffer); //依bbi.txt的编码类型选择合适的编码,若是不调整会乱码 res = EncodingUtils.getString(buffer, "UTF-8"); //res =EncodingUtils.getString(buffer, "BIG5"); //res =EncodingUtils.getString(buffer, "UNICODE"); in.close(); } catch(Exception e){ e.printStackTrace(); } return res ; }
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; }