【发布时间】:2020-04-26 14:33:14
【问题描述】:
我正在使用 PdfBox-Android (https://github.com/TomRoush/PdfBox-Android) 库来读取 PDF 文件。当用户单击一个按钮(w/id file1)时,会弹出一个文件选择器,他或她可以在其中选择要读入的 pdf 文件。但是,当我从用户选择的文件并使用 EITHER getString() 或 getPath() 获取文件名,我收到以下错误(使用toString()):
异常:java.io.FileNotFoundException: 内容:/com.android.providers.downloads.documents/document/7306:打开 失败:ENOENT(没有这样的文件或目录)
使用getPath() 会出现以下错误:
异常 java.io.FileNotFoundException: /document/7097: 打开失败: ENOENT (No 这样的文件或目录)
下面是我的代码:
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)
}
【问题讨论】:
-
PDDocument.load(File(uri?.path))不要尝试从内容方案的 uri 创建文件。像PDDocument.load(uri)这样的东西应该是可能的。如果不要求他们实施它。 -
Android 中有没有办法将 URI 加载到流中?如果是,则传递该流。
标签: java android file kotlin io