使用Java读取Android上的文件夹中的所有文件时出错

时间:2017-05-15 15:45:50

标签: java android file directory

我的应用在运行时崩溃了。我在Android 5.1(Lollipop)上尝试过它。此应用需要读取文件夹中的所有文件。该文件夹在SD卡上下载。

Listview工作正常,没有错误。来源是:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] files = getAllFilesInFolder(Environment.getExternalStorageDirectory().toString() + "/download");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.LargeTextInList, files);
        ListView list = (ListView) findViewById(R.id.listView);
        list.setAdapter(adapter);

        list.setOnItemClickListener(new ItemList());
    }

    String[] getAllFilesInFolder(String path){
        ArrayList<String> result = new ArrayList<String>(); //ArrayList cause you don't know how many files there is
        File folder = new File(path); //This is just to cast to a File type since you pass it as a String
        File[] filesInFolder = folder.listFiles(); // This returns all the folders and files in your path
        for (File file : filesInFolder) { //For each of the entries do:
            if (!file.isDirectory()) { //check that it's not a dir
                result.add(new String(file.getName())); //push the filename as a string
            }
        }

        String[] files = new String[ result.size() ];
        result.toArray( files );
        return files;
    }

    class ItemList implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
            ViewGroup vg = (ViewGroup) view;
            TextView tv = (TextView) vg.findViewById(R.id.LargeTextInList);
            Toast.makeText(MainActivity.this, tv.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您需要添加权限  1)在AndroidManifest中添加

  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.myApp">   

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

2)然后在您的活动请求中,这可以从api 21 +

获得权限
private static final int PERMISSIONS_READ_STORE = 2;

private void requestPermissions() {
    String [] permissions=new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String permission:permissions) {
        if (ContextCompat.checkSelfPermission(this,permission )!= PackageManager.PERMISSION_GRANTED){
            listPermissionsNeeded.add(permission);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSIONS_READ_STORE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if(requestCode == PERMISSIONS_READ_STORE) {
        if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          // Permissions ok get the files
        }
    }else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

在获取文件之前调用requestPermissions()