【问题标题】:Android - cant save file to storageAndroid - 无法将文件保存到存储
【发布时间】:2016-03-05 02:09:40
【问题描述】:

我尝试使用以下代码保存从互联网下载的文件

public static String saveToSdCard(Bitmap bitmap, String filename) {

    String stored = null;

    File sdcard = Environment.getExternalStorageDirectory() ;

    File folder = new File(sdcard.getAbsoluteFile(), ".tanks");
    boolean success = true; //the dot makes this directory hidden to the user

    if (!folder.exists()) {
        success = folder.mkdir();
    }

    if (success) {
        File file = new File(folder.getAbsoluteFile(), filename + ".jpg") ;
        if (file.exists())
            return stored ;

        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            stored = "success";
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return stored;
}

但在运行时我得到类似的错误

03-04 20:42:51.080 8972-8972/com.example.me.demo2 E/BitmapFactory:无法解码流:java.io.FileNotFoundException: /storage/emulated/0/.tanks/4a100abb-0e55-4062-8c37-f11f4189e618.jpg:打开失败:ENOENT(没有这样的文件或目录)

在我的应用清单文件中,我添加了权限

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

但是当我启动应用程序时,没有提示要求授予权限。

我是不是做错了什么?

【问题讨论】:

标签: android


【解决方案1】:

尝试删除文件夹并手动创建它。根据您的代码,

File tempFolder = new File(sdcard.getAbsoluteFile(), ".tanks");
tempFolder.mkdirs();
if (success) {
    File file = new File(tempFolder, filename + ".jpg") ;
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 2023-03-10
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2018-05-30
    • 2020-02-11
    相关资源
    最近更新 更多