Save a File on External Storage

Save a File on External Storage

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:

Public files
Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.

For example, photos captured by your app or other downloaded files.
Private files
Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don’t provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app’s external private directory.

For example, additional resources downloaded by your app or temporary media files.

If you want to save public files on the external storage, use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES. For example:
public File getAlbumStorageDir(String albumName) {
    // Get the directory for the user's public pictures directory. 
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}
If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you’d like. Each directory created this way is added to a parent directory that encapsulates all your app’s external storage files, which the system deletes when the user uninstalls your app.

For example, here’s a method you can use to create a directory for an individual photo album:

public File getAlbumStorageDir(Context context, String albumName) {
    // Get the directory for the app's private pictures directory. 
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}
这段代码是一个静态方法,用于保存数据到文件中。下面对每一行代码进行解释: 1. `public static boolean saveFile(Context context, String fileName, String data, boolean append){}` 这是方法的声明,指定方法名称为saveFile,参数类型为Context、String、String、boolean,返回类型为boolean。 2. `String path = Environment.getExternalStorageDirectory()+"/osnavData/";` 获取外部存储目录的路径,并在路径后面添加一个名为osnavData的文件夹名,用于存储文件。 3. `String filePath = path+fileName;` 将文件名添加到路径后面,生成完整的文件路径。 4. `File folder = new File(path);` 创建一个名为folder的File对象,代表存储文件的目录。 5. `File file = new File(filePath);` 创建一个名为fileFile对象,代表要保存数据的文件。 6. `if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){}` 判断当前设备的Android版本是否小于23(Build.VERSION_CODES.M)。 7. `threadToast(context, "版本号:"+Build.VERSION.SDK_INT);` 如果版本小于23,则调用threadToast方法,弹出一个Toast提示当前的Android版本号。 8. `return false;` 并返回false,表示保存文件失败。 9. `} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {` 如果版本号大于或等于30(Build.VERSION_CODES.R)。 10. `if(!Environment.isExternalStorageManager()){` 判断当前应用是否被授予管理所有文件的权限。 11. `Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);` 如果没有被授予权限,则创建一个Intent对象,跳转到系统设置界面,让用户手动授权。 12. `context.startActivity(intent);` 启动Intent对象,跳转到系统设置界面。 13. `return false;` 并返回false,表示保存文件失败。 14. `} else{` 如果版本号在23到29之间。 15. `if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {` 检查当前应用是否被授予写外部存储的权限。 16. `ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_WRITEFILE);` 如果没有被授予权限,则请求授权,弹出授权对话框,并等待用户授权。 17. `return false;` 并返回false,表示保存文件失败。 18. `}` 如果已经被授予权限,则继续执行下面的代码。 在这段代码中,没有对权限请求的结果进行处理,需要在onRequestPermissionsResult方法中处理授权结果。 该方法的主要作用是判断当前设备的Android版本和应用是否被授予权限,如果没有被授予权限,则请求授权,并在授权完成后保存数据到文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值