簡體   English   中英

如何列出我的 android 設備中的所有 pdf 文件

[英]how to list all pdf files in my android device

我找到了有關如何獲取所有圖像的代碼。

有人能告訴我如何在內部存儲和外部存儲中只獲取 .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]);
    } 

可能的解決方案可以轉到每個文件夾並檢查 .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());

您應該能夠通過 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());
}

(注意:此主題可能與另一個較舊的問題重復,但它沒有公認的答案,因此無法對其進行標記)

如果您使用 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 做類似的事情

你可以試試這個: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);
    }

您可以使用以下內容列出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您可以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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM