存储在内部还是外部?
*Internal storage(内部)
** getFileDir():返回一个File,代表了我们app的internal目录。
** getCacheDir():返回一个File,代表了我们app的internal缓存目录。
*External storage(外部)
MainActivity中创建文档写入数据:
testFileDemo();
/**
*the demo for test file.
*/
private void testFileDemo(){
//create a new file of test.txt in the internal storage
File file = new File(getFilesDir(),"test.txt");
//打印路径
Log.i("MainActivity","getFileDir:"+getFileDir().getAbsolutePath());
Log.i("MainActivity","file path:"+file.getAbsolutePath());
String string = "That is right!";
//抛出异常
try{
boolean isSuccess = file.createNewFile();
} catch (IOException e){
Log.i("MainActivity","test.txt create error:"+e.toString());
e.printStackTrace();
}
try{
FileOutputStream fileOutputStraem = openFileOutput("test2.txt",Context.MODE_PRIVATE);
try{
fileOutputStream.write(string.getBytes());
fileOutputStream.close();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch (FileNotFoundException e){
e.printStackTrace();
}
//check externalcstorage state
String state = Environment.getExternalStorageState();
if(TextUtils.equals(state,Environment.MEDIA_MOUNTED)){
......
}
}
读取各目录下的文件
- 操作assets目录下的文件
void testAssets(){
//第一种,直接读取路径
WebView webView = new Webview(this);
webView.loadUrl("file:///android_asset/test.html");
try{
//open的只能是文件,不能使文件夹
InputStream inputStream = getResources().getAssets().open("test.html");
} catch (IOException e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"文件读取异常",Toast.LENGTH_SHORT).show();
}
//读列表
string[] filenames = getAssets().list("images");
//读图片
InputStream inputStream = getAssets().open("images/dream.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
//读音乐
AssetsFileDescriptor assetFileDescriptor = getAssets().openFd("libai.mp3");
MediaPlayer player = new MediaPlayer();
player.reset();
player.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength());
player.prepare();
player.start();
}
- 操作res目录下的文件
- 操作raw目录下的文件
void testResFile(){
InputStream inputStream = getResources().openRawRescource(R.raw.libai);
getRescource().getColor(R.color.abc_background_cache_hint_selector_material_dark);
getRescource().getDrawable();
}
- 操作sd卡文件
void testSDCard(){
File file = new File("/sdcard/test/a.txt");
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
Environment.getDataDirectory();//获取Android中的data数据目录
Environment.getDownloadCacheDirectory();
Environment.getExternalStorageDirectory();
}
获取External存储的权限:android.permission.EXTERNAL_STORAGE
在AndroidMainifest.xml文件中注册权限:
- 获取申请上网权限:
<uses-permission android:name="android.permission.INTERENT"/>
- 写外部存储的权限(*注:应用本身就可以读写内部内存,所以无需注册):
<uses-permission android:name = "android.perission.WRITE_EXTERNAL_STORAGE"/>
应用选择安装在内部空间或外部空间(外部sd卡):
android:installLocation = "preferExternal"