搜索Android设备中存在的所有.pdf文件

slmsl1lt  于 2022-12-31  发布在  Android
关注(0)|答案(5)|浏览(214)

如何通过编程方式搜索Android设备中存在的所有 .pdf.doc 文件?

qkf9rpyu

qkf9rpyu1#

尝试使用下面的代码。这将为您工作。

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

    File listFile[] = dir.listFiles();

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

            if (listFile[i].isDirectory()) {
                walkdir(listFile[i]);
            } else {
              if (listFile[i].getName().endsWith(pdfPattern)){
                                  //Do whatever you want

              }
            }
        }
    }
}

要搜索整个SD卡,请使用以下命令调用此函数:

walkdir(Environment.getExternalStorageDirectory());
ulydmbyx

ulydmbyx2#

请查看 * 文件 列表 *。
基本上,获取一个起始目录,使用过滤器(FilenameFilter)调用“list”,然后遍历子目录。我不确定是否有一个函数可以为您完成所有这些操作。

hrirmatl

hrirmatl3#

从此处下载源代码(Open pdf file from SD card in android programmatically

在Gradle文件中添加此依赖关系:

compile ‘com.github.barteksc:android-pdf-viewer:2.0.3’

主要活动.java:

package com.pdffilefromsdcard;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ListView lv_pdf;
    public static ArrayList<File> fileList = new ArrayList<File>();
    PDFAdapter obj_adapter;
    public static int REQUEST_PERMISSIONS = 1;
    boolean boolean_permission;
    File dir;

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

    private void init() {

        lv_pdf = (ListView) findViewById(R.id.lv_pdf);
        dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        fn_permission();
        lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
                intent.putExtra(“position”, i);
                startActivity(intent);

                Log.e(“Position”, i + “”);
            }
        });
    }

    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()) {
                getfile(listFile[i]);
            }
            else {

                boolean booleanpdf = false;
                if (listFile[i].getName().endsWith(“.pdf”)) {

                    for (int j = 0; j < fileList.size(); j++) {
                        if (fileList.get(j).getName().equals(listFile[i].getName())) {
                            booleanpdf = true;
                        }
                        else {
                        }
                    }

                    if (booleanpdf) {
                        booleanpdf = false;
                    }
                    else {
                        fileList.add(listFile[i]);
                        }
                    }
                }
            }
        }
        return fileList;
    }

    private void fn_permission() {
        if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
            }
            else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_PERMISSIONS);
            }
        }
        else {
            boolean_permission = true;

            getfile(dir);

            obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
            lv_pdf.setAdapter(obj_adapter);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                boolean_permission = true;
                getfile(dir);

                obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
                lv_pdf.setAdapter(obj_adapter);

            }
            else {
                Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();

            }
        }
    }
}

个人资料活动.java:

package com.pdffilefromsdcard;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.io.File;
import java.util.List;

public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {

    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;
    String TAG=”PdfActivity”;
    int position=-1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf);
        init();
    }

    private void init(){
        pdfView= (PDFView)findViewById(R.id.pdfView);
        position = getIntent().getIntExtra(“position”,-1);
        displayFromSdcard();
    }

    private void displayFromSdcard() {
        pdfFileName = MainActivity.fileList.get(position).getName();

        pdfView.fromFile(MainActivity.fileList.get(position))
            .defaultPage(pageNumber)
            .enableSwipe(true)

            .swipeHorizontal(false)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), “-“);
    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + “-“);
            }
        }
    }
}
5w9g7ksd

5w9g7ksd4#

看一下堆栈溢出问题 How can I get all audio files from the SD card on Android?
更改文件的扩展名,就像如果你想要所有的PDF文件,然后扩展名“.pdf”。使用这个从设备上获取所有的PDF文件。

yhxst69z

yhxst69z5#

我在我的旧项目中找到了这个方法。这个函数将为您获取PDF文件及其信息。

  • ManageFIleInfoForRecycler* 是我用来存储文件信息的自定义类。

“存储器”传递为“外部”。

public ArrayList<ManageFIleInfoForRecycler> fileList(String storage) {

    ArrayList< ManageFIleInfoForRecycler > fileInfo = new ArrayList<>();

    // Can give any file type, "doc", "pdf", etc.
    String pdf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
    int j = 0;

    Uri table = MediaStore.Files.getContentUri(storage);

    // Column
    String[] column = {MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.TITLE};

    // Where
    String where = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
    String[] args = new String[]{pdf};

    Cursor fileCursor = getApplicationContext().getContentResolver().query(table, column, where, args, null);

    String [] filesLists = new String[]{};
    while (fileCursor.moveToNext()) {

        int pathString = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
        int nameIndex = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE);
        String path = fileCursor.getString(pathString);
        String name = fileCursor.getString(nameIndex);
        ManageFIleInfoForRecycler temp = new ManageFIleInfoForRecycler();
        temp.filePath = path;
        temp.fileName = name;
        fileInfo.add(temp);
    }
    return fileInfo;
}

相关问题