Android: Невозможно прочитать пользователь PDF-файла, выбранный с помощью ОБА getString () и getPath () из URI - PullRequest
0 голосов
/ 09 января 2020

Я использую библиотеку PdfBox- Android (https://github.com/TomRoush/PdfBox-Android) для чтения в файлах PDF. Когда пользователь нажимает кнопку (w / id file1 ), появляется средство выбора файла, где он или она может выбрать файл PDF для чтения. Однако, когда я получаю URI из выбранного пользователем файла и использовать EITHER getString () или getPath () для получения имени файла, я получаю следующую ошибку (используя toString()):

Исключение: java .io .FileNotFoundException: content: /com.android.providers.downloads.documents/document/7306: открыть не удалось: ENOENT (нет такого файла или каталога)

и следующая ошибка при использовании getPath() :

Исключение java .io.FileNotFoundException: / document / 7097: открытие не удалось: ENOENT (нет такого файла или каталога)

Ниже мой код:

import com.tom_roush.pdfbox.pdmodel.PDDocument
import com.tom_roush.pdfbox.text.PDFTextStripper
import com.tom_roush.pdfbox.util.PDFBoxResourceLoader

// File picker implementation
private fun chooseFile(view:View) {
    println("chooseFile activated!");
    var selectFile = Intent(Intent.ACTION_GET_CONTENT)
    selectFile.type = "*/*"
    selectFile = Intent.createChooser(selectFile, "Choose a file")
    startActivityForResult(selectFile, READ_IN_FILE)
}


/* After startActivityForResult is executed, when the selectFile Intent is completed, onActivityResult is executed with
   the result code READ_IN_FILE.*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == READ_IN_FILE) { // Step 1: When a result has been received, check if it is the result for READ_IN_FILE
        if (resultCode == Activity.RESULT_OK) { // Step 2: Check if the operation to retrieve thea ctivity's result is successful
            // Attempt to retrieve the file
            try {
                // Retrieve the true file path of the file
                var uri: Uri? = data?.getData();
                    // Initialize and load the PDF document reader for the file the user selected
                    var document = PDDocument.load(File(uri?.path));

                    // Read in the text of the PDF document
                    var documentText = PDFTextStripper().getText(document);

                    println("documentText = " + documentText);

                    document.close();
            } catch (e: Exception) { // If the app failed to attempt to retrieve the error file, throw an error alert
                println("EXCEPTION: " + e.toString());
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Initialize the PDFBox library's resource loader
    PDFBoxResourceLoader.init(applicationContext);

    setContentView(R.layout.activity_main)

    var file1:Button = findViewById(R.id.file1);
    file1.setOnClickListener(::chooseFile)
}

1 Ответ

0 голосов
/ 09 января 2020

Перед вызовом PDFBox настоятельно рекомендуется инициализировать загрузчик ресурсов библиотеки. Добавьте следующую строку перед вызовом методов PDFBox:

PDFBoxResourceLoader.init(getApplicationContext());

Поэтому отредактируйте свой код

.....
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
   setContentView(R.layout.activity_main)

   PDFBoxResourceLoader.init(getApplicationContext());//call this
   var file1:Button = findViewById(R.id.file1);
   file1.setOnClickListener(::chooseFile)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...