Listing files in “/sdcard/” returns null?

こ雲淡風輕ζ 提交于 2019-12-13 07:24:15

问题


I have an app that needs access to an android phone's internal storage, such as the Download folder. However when I try to list the files it alimport

java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class Main extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        File root = new File("/"); // Works
        File mnt = new File("/mnt/"); // Works
        File mnt2 = new File("/mnt/m_internal_storage"); // Crashes
        File cus = new File("/custom/"); // Works
        File f = new File("/sdcard/"); // Crashes
        String[] s =  f.list();
        for (int x = 0; x < s.length; x++) {
            Log.println(Log.ASSERT, "#", s[x]);
        }
    }
}

This code will print every file in the directory. It works with root, mnt & cus but crashes when it tries to get the list of f & mnt2, returning a null array to s. How do I access the internal file storage?

I have also tried using Environment's functions with most failing and I even have Read/Write permissions for External Storage enabled.

Compiling for 7.0. Targeting API 23. Min sdk API 18.


回答1:


I have an app that needs access to an android phone's internal storage, such as the Download folder.

The Download folder that users see is on what the Android SDK calls external storage.

How do I access the internal file storage?

Use Environment.getExternalStorageDirectory(). Never hardcode paths. For example, vanishingly few devices on the face of the planet have /mnt/m_internal_storage, /custom/, or /sdacard/.

I have also tried using Environment's functions with most failing and I even have Read/Write permissions for External Storage enabled.

Perhaps you did not implement runtime permissions.




回答2:


In your code it is "File f = new File("/sdacard/"); // Crashes", which should be "/sdcard/".




回答3:


if you want internal file of your app, means in app.package

/sdcard/data/data/pack_name/files/fileName

you need to access it like this

File p = getApplicationContext().getFileStreamPath("FileName");

Edit other than this you have to ask for runtime permissions and Download Path is not Internal Storage! it defines as external. everything that normal users can access (without root) in file manager is external storage. internal storage is not like internal sdcard and then micro sdcard. Internal Storage is what belong to ur package read it: https://developer.android.com/guide/topics/permissions/requesting.html



来源:https://stackoverflow.com/questions/42519577/listing-files-in-sdcard-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!