版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/w_jingjing0428/article/details/52205027
今天住的地方熱哭我,吐槽完了。。。
準備工作
- 申請權限:
讀取外部文件的權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- 一些方法:
- getDir(String name ,int mode):獲取應用程序的數據文件夾下獲取或者創建name對應的子目錄
- getFilesDir():數據文件夾的絕對路徑
- String[] fileList():數據文件夾的全部文件
- deleteFile(String):刪除指定文件
讀取內部文件
新建一個內部文件:
File file = new File(getFilesDir(), "text.txt");
try {
boolean isSuccess = file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
寫文件:
try {
FileOutputStream files = openFileOutput("text2.txt" , Context.MODE_PRIVATE);
files.write(string.getBytes());
files.close();
} catch (IOException e) {
e.printStackTrace();
}
還有輸入流:FileInputStream openFileInput(String name)。
讀寫SD卡
- 先判斷手機上是否插入了SD卡
String state = Environment.getExternalStorageState();
if(TextUtils.equals(state, Environment.MEDIA_MOUNTED)){
//do some thing
}
- 獲取外部存儲器,就是sd卡的目錄
File sd = Environment.getExternalStorageDirectory();
//還有其他
String filePath = Environment.getDownloadCacheDirectory().getAbsolutePath();
Environment.getDataDirectory();//獲取android的data目錄
Environment.getDownloadCacheDirectory();//獲取下載目錄
- 然後就是各種讀寫操作
讀取Assets
- open後面必須是一個文件,不能是文件夾
void testAssets(){
//第一種,直接讀路徑
WebView webview = new WebView(this);
webview.loadUrl("file:///android_asset/text.html");
try {
InputStream inputStream = getResources().getAssets().open("text.html");
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(FirstActivity.this, "文件讀取錯誤", Toast.LENGTH_LONG);
}
- 讀取列表
//讀列表
try {
String[] fileNames = getAssets().list("images");
} catch (IOException e) {
e.printStackTrace();
}
- 讀音樂文件
try {
AssetFileDescriptor a = getAssets().openFd("my.mp3");
MediaPlayer m = new MediaPlayer();
m.setDataSource(
a.getFileDescriptor(),
a.getStartOffset(),
a.getLength()
);
} catch (IOException e) {
e.printStackTrace();
}
- 讀圖片
//讀圖片
try {
InputStream inputStream = getAssets().open("imges/dpg.pg");
Bitmap imageView = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
res文件
InputStream input = getResource().openRawResouce(R.raw.XXX);
這樣 就可以訪問
res和assets區別
相同點:原封不動的打包在apk裏
不同點:
- assets:什麼都不動;
- res:會映射成一個int值
簡單羅列,hehehe…