访问 getExternalStorageDirectory

9

我正在尝试使用一些相当简单的Android代码按照以下逻辑访问文件夹:

public void try_to_navigate_local_dir(){
    Environment e = new Environment();
    ArrayList<String> filesList = new ArrayList<String>();
    String sd_card = Environment.getExternalStorageDirectory().toString() + "/subdir_x";
    File file = new File( sd_card ) ;
    File list[] = file.listFiles();
    for( int i=0; i< list.length; i++) {
        filesList.add( list[i].getName() );
    }
}

这里的subdir_x是由我的手机上的另一个应用程序创建的。

我可以使用文件管理器查看这些文件夹,但当我尝试使用file.listFiles()时,我的代码返回null。

我该如何访问这些文件?


https://dev59.com/J1wX5IYBdhLWcg3w-Thv#41221852 - Bipin Bharti
3个回答

10

我在 Marshmallow (6.0) 上尝试了这个逻辑:

  1. 确保您的清单文件中有以下内容:

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

  1. when try to access external storage please check the permission before entering the logic to read directory :

    public void checkPermissionReadStorage(Activity activity){
             if (ContextCompat.checkSelfPermission(activity,      Manifest.permission.READ_EXTERNAL_STORAGE) !=     PackageManager.PERMISSION_GRANTED) {
    
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
    
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
    
            } else {
    
                // No explanation needed, we can request the permission.
    
                ActivityCompat.requestPermissions(activity,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_STORAGE);
    
                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }
    
  2. and then override this method in your activity :

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PermissionManager.MY_PERMISSIONS_REQUEST_READ_STORAGE: {
                //premission to read storage
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
    
                } else {
    
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(SnapSellAddActivity.this, "We Need permission Storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }
    
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
    
  3. after that you can finally read the external storage in android devices, I tried like this method to read directory in external storage :

    public File getPreviewTempExternalDirectory(Context context) {
        File previewDir = new File(context.getExternalFilesDir(null), PLACE YOUT DIR HERE);
        if (!previewDir.exists()) previewDir.mkdir();
        return previewDir;
    }
    

    and now you have the directory, you can list file or create file there. hope it helps.


3
在Marshmallow版本之前,请按照@Cory Charlton的答案操作。然而,他在Android Marshmallow(6.0)的回答将不起作用。
实际上,在Android 6.0(API级别23)中,我们不再拥有以下权限。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

了解更多信息,请查看以下问题:

顺便说一下,Environment e = new Environment();是无用的,请将其删除。


0

请确保您的 AndroidManifest.xml 文件具有适当的权限:

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

下一个可能的问题可能是您的文件名。 我在我的一个应用程序中使用以下内容,它可以正常工作(请注意末尾斜杠和缺少前导斜杠):
directory = new File(Environment.getExternalStorageDirectory(), "Subdirectory/")
final File[] files = directory.listFiles();

下一个问题可能是路径Environment.getExternalStorageDirectory()提供给您的。较新的设备在内部存储器上有一个模拟SD卡的分区,Environment.getExternalStorageDirectory()可能会返回这个模拟SD卡而不是真实的SD卡。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接