如何在我的Android设备中列出所有pdf文件

时间:2015-07-27 11:42:57

标签: android pdf

我找到了关于如何获取所有图像的代码。

有人可以告诉我如何才能在内部存储空间和外部存储空间中获取.pdf文件?

final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    //Stores all the images from the gallery in Cursor
    Cursor cursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    //Total number of images
    int count = cursor.getCount();

    //Create an array to store path to all the images
    String[] arrPath = new String[count];

    for (int i = 0; i < count; i++) {
        cursor.moveToPosition(i);
        int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        //Store the path of the image
        arrPath[i]= cursor.getString(dataColumnIndex);
        Log.i("PATH", arrPath[i]);
    } 

5 个答案:

答案 0 :(得分:1)

可能的解决方案可以转到每个文件夹并检查.pdf是否存在,如果是,您可以对该文件执行哪些操作

public void Search_Dir(File dir) {
  String pdfPattern = ".pdf";

File FileList[] = dir.listFiles();

if (FileList != null) {
    for (int i = 0; i < FileList.length; i++) {

        if (FileList[i].isDirectory()) {
            Search_Dir(FileList[i]);
        } else {
          if (FileList[i].getName().endsWith(pdfPattern)){
                              //here you have that file.

          }
        }
    }
  }    
}

和函数调用将是

Search_Dir(Environment.getExternalStorageDirectory());

答案 1 :(得分:1)

您应该能够通过Android的MediaStore.Files列出所有这些文件,而无需手动浏览所有设备的文件夹。

例如:

String selection = "_data LIKE '%.pdf'"
try (Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Files.getContentUri("external"), null, selection, null, "_id DESC")) {
    if (cursor== null || cursor.getCount() <= 0 || !cursor.moveToFirst()) {
        // this means error, or simply no results found
        return;
    }
    do {
        // your logic goes here
    } while (cursor.moveToNext());
}

(注意:本主题可能与another, older question相同,但没有可接受的答案,因此无法标记它)

答案 2 :(得分:0)

你可以试试这个: 1.)

private ListView mListView;
private ArrayList<AttachmentModel> mAttachmentList = new ArrayList<>();
private ArrayList<File> fileList = new ArrayList<File>();
mListView = (ListView)findViewById(R.id.listAttachments);
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
getfile(dir );
setAdapter();

2。)

public ArrayList<File> getfile(File dir) {
        File listFile[] = dir.listFiles();
        if (listFile != null && listFile.length > 0) {
            for (int i = 0; i < listFile.length; i++) {

                if (listFile[i].isDirectory()) {
                    fileList.add(listFile[i]);
                    getfile(listFile[i]);

                } else {
                    if (listFile[i].getName().endsWith(".pdf")
                            || listFile[i].getName().endsWith(".xls")
                            || listFile[i].getName().endsWith(".jpg")
                            || listFile[i].getName().endsWith(".jpeg")
                            || listFile[i].getName().endsWith(".png")
                            || listFile[i].getName().endsWith(".doc"))
                    {
                        fileList.add(listFile[i]);
                        mAttachmentList.add(new AttachmentModel(listFile[i].getName()));
                    }
                }
            }
        }
        return fileList;
    }

3。)

private void setAdapter()
    {
        AttachmentAdapter itemsAdapter = new AttachmentAdapter(AttachmentFileList.this);
        ArrayList<AttachmentModel> list = new ArrayList<>();
        itemsAdapter.setData(mAttachmentList);
        mListView.setAdapter(itemsAdapter);
    }

答案 3 :(得分:0)

如果您使用Kotlin,我认为这是最简洁的方法

val ROOT_DIR = Environment.getExternalStorageDirectory().absolutePath
val ANDROID_DIR = File("$ROOT_DIR/Android")
val DATA_DIR = File("$ROOT_DIR/data")
File(ROOT_DIR).walk()
               // befor entering this dir check if
               .onEnter{ !it.isHidden // it is not hidden
                         && it != ANDROID_DIR // it is not Android directory
                         && it != DATA_DIR // it is not data directory
                && !File(it, ".nomedia").exists() //there is no .nomedia file inside
               }.filter { it.extension == "pdf" }
               .toList()

您可以对java8流或RxJava进行类似的思考

答案 4 :(得分:0)

您可以使用以下内容列出PDF个文档(这不会列出设备上未知的PDF)

// Use android.provider.MediaStore

String[] projection = {
    MediaStore.Files.FileColumns._ID,
    MediaStore.Files.FileColumns.MIME_TYPE,
    MediaStore.Files.FileColumns.DATE_ADDED,
    MediaStore.Files.FileColumns.DATE_MODIFIED,
    MediaStore.Files.FileColumns.DISPLAY_NAME,
    MediaStore.Files.FileColumns.TITLE,
    MediaStore.Files.FileColumns.SIZE,
};

String mimeType = "application/pdf";

String whereClause = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')";
String orderBy = MediaStore.Files.FileColumns.SIZE + " DESC";
Cursor cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"),
                                           projection,
                                           whereClause,
                                           null,
                                           orderBy);

如果您不仅要拥有PDF个文件(例如DocX),还可以对where子句进行一些修改以适应您的需求:

String whereClause = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')"
          + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd%'"

然后遍历光标以检索文档:

int idCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
int mimeCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE);
int addedCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_ADDED);
int modifiedCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED);
int nameCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME);
int titleCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE);
int sizeCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE);

if (cursor.moveToFirst()) {
    do {
        Uri fileUri = Uri.withAppendedPath(MediaStore.Files.getContentUri("external"), cursor.getString(idCol));
        String mimeType = cursor.getString(mimeCol);
        long dateAdded = cursor.getLong(addedCol);
        long dateModified = cursor.getLong(modifiedCol);
        // ...
    } while (cursor.moveToNext());
}