Android将文件保存到外部存储

And*_*oid 82 storage android file external

我有一个问题,在我的Android应用程序上创建一个目录并将文件保存到它.我正在使用这段代码来执行此操作:

String filename = "MyApp/MediaTag/MediaTag-"+objectId+".png";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;

fos = new FileOutputStream(file);
fos.write(mediaTagBuffer);
fos.flush();
fos.close();
Run Code Online (Sandbox Code Playgroud)

但这是一个例外:

java.io.FileNotFoundException:/mnt/sdcard/MyApp/MediaCard/MediaCard-0.png(没有这样的文件或目录)

在那条线上: fos = new FileOutputStream(file);

如果我将文件名设置为:"MyApp/MediaTag-"+objectId+"它正在工作,但如果我尝试创建并将文件保存到另一个目录,则会抛出异常.那么任何想法我做错了什么?

还有一个问题:有没有办法让我的文件在外部存储中保密,这样用户就无法在图库中看到它们,只有当他连接他的设备时Disk Drive

Raj*_*ddy 179

使用此功能可将位图保存在SD卡中

private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
     if (!myDir.exists()) {
                    myDir.mkdirs();
                }
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ())
      file.delete (); 
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
         e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

并在清单中添加此项

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
Run Code Online (Sandbox Code Playgroud)

编辑:通过使用此行,您将能够在图库视图中查看已保存的图像.

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                         Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Run Code Online (Sandbox Code Playgroud)

看看这个链接也是http://rajareddypolam.wordpress.com/?p=3&preview=true

  • 你仍然应该使用`Environment.getExternalStorageDirectory()`而不是`/ sdcard`. (9认同)
  • 请使用`finally`并且不要捕获泛型`Exception` (7认同)
  • 使用`Intent.ACTION_MEDIA_MOUNTED`是不合适的,并且不适用于KitKat.广播的正确意图是"新意图(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(file))" (3认同)
  • @LiamGeorgeBetsworth以上描述的所有行为都可以*在**KitKat**之前*. (2认同)

Yar*_*Yar 24

RajaReddy提供的代码不再适用于KitKat

这个(2个变化):

private void saveImageToExternalStorage(Bitmap finalBitmap) {
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }


    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
    });

}
Run Code Online (Sandbox Code Playgroud)

  • 我正在获取uri null? (2认同)

Joã*_*cho 11

更新 2018,SDK >= 23。

现在您还应该使用以下命令检查用户是否已授予外部存储权限:

public boolean isStoragePermissionGranted() {
    String TAG = "Storage Permission";
    if (Build.VERSION.SDK_INT >= 23) {
        if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG, "Permission is granted");
            return true;
        } else {
            Log.v(TAG, "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

public void saveImageBitmap(Bitmap image_bitmap, String image_name) {
    String root = Environment.getExternalStorageDirectory().toString();
    if (isStoragePermissionGranted()) { // check or ask permission
        File myDir = new File(root, "/saved_images");
        if (!myDir.exists()) {
            myDir.mkdirs();
        }
        String fname = "Image-" + image_name + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile(); // if file already exists will do nothing
            FileOutputStream out = new FileOutputStream(file);
            image_bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        MediaScannerConnection.scanFile(this, new String[]{file.toString()}, new String[]{file.getName()}, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,添加AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
Run Code Online (Sandbox Code Playgroud)


Dev*_*bby 5

你需要这个权限

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

public boolean saveImageOnExternalData(String filePath, byte[] fileData) {

    boolean isFileSaved = false;
    try {
        File f = new File(filePath);
        if (f.exists())
            f.delete();
        f.createNewFile();
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(fileData);
        fos.flush();
        fos.close();
        isFileSaved = true;
        // File Saved
    } catch (FileNotFoundException e) {
        System.out.println("FileNotFoundException");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IOException");
        e.printStackTrace();
    }
    return isFileSaved;
    // File Not Saved
}
Run Code Online (Sandbox Code Playgroud)