【Android】数据存储-随心所欲地管理文件

存储在内部还是外部?

内部存储
外部存储

1、授权相关设置

获取外部存储的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

安装在sd中:

android:installLocation="preferExternal"

用的位置:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jsc4.aboutactivity"
    android:installLocation="preferExternal"  这里
    >

2、内部存储

getFileDir()  返回一个File,代表了我们app的internal目录
getCacheDir()  返回一个File,代表了我们app的internal缓存目录

使用:

 /**
     * 测试文件
     */
    private void testFileDemo() {
    
    
        // 在内部存储中创建新文件test.txt
        File file = new File(getFilesDir(), "test.txt");
        Log.i(TAG, "testFileDemo:getFilesDir():"+ getFilesDir().getAbsolutePath());
        Log.i(TAG, "testFileDemo:file path:"+ file.getAbsolutePath());
        // getFilesDir():/data/user/0/com.jsc4.aboutactivity/files
        // file path:/data/user/0/com.jsc4.aboutactivity/files/test.txt

        try {
    
    
            boolean isSuccess = file.createNewFile();
        } catch (IOException e) {
    
    
            Log.i(TAG, "test.txt create error: "+ e.toString());
            e.printStackTrace();
        }

        String str = "随便写点什么";
        try {
    
    
            FileOutputStream fileOutputStream = openFileOutput("test2.txt", Context.MODE_PRIVATE);
            fileOutputStream.write(str.getBytes());
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

3、外部存储,检测SD卡状态

String state = Environment.getExternalStorageState();
if(TextUtils.equals(state, Environment.MEDIA_MOUNTED)){
    
    

}

4、读取各个目录下的文件

assets:
编译时原封不动放在apk中,不会映射到R.java文件中
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_LONG).show();
        }

        // 读取文件名列表
        try {
    
    
            String[] fileNames = getAssets().list("images/");
            Log.i(TAG, "testAssets: "+ Arrays.toString(fileNames));
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        // 读一张图片并显示
        try {
    
    
            InputStream inputStream = getAssets().open("images/square32green.png");
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            ImageView imageView = new ImageView(this);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        // 读音频
        try {
    
    
            Log.i(TAG, "testAssets: 播放音乐");
            AssetFileDescriptor assetFileDescriptor = getAssets().openFd("lovelove.mps");
            MediaPlayer player = new MediaPlayer();
            player.reset();
            player.setDataSource(
                    assetFileDescriptor.getFileDescriptor(),
                    assetFileDescriptor.getStartOffset(),
                    assetFileDescriptor.getLength());
            player.prepare();
            player.start();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

raw:
编译时也是原封不动放在apk中,但它会映射到R.java文件中
raw中不可以再建立目录结构

    void testResFile(){
    
    
        InputStream inputStream = getResources().openRawResource(R.raw.lovelove);

        getResources().getColor(R.color.colorAccent);
        getResources().getString(R.string.age);
        getResources().getDrawable(R.drawable.ic_launcher_background);
    }

sd卡:

File file = new File("/sdcard/test/a.txt");  这里的SD卡路径未必正确

SD卡路径一般通过这个方法去获取
File tempFile = Environment.getExternalStorageDirectory().getAbsoluteFile();

其他获取路径的方法:
Environment.getDataDirectory(); 获取Android中的data数据目录
Environment.getDownloadCacheDirectory();
Environment.getExternalStorageDirectory();

猜你喜欢

转载自blog.csdn.net/qq_30885821/article/details/108904894