我正在尝试使用 android studio java(api 26 min 和 api33 是模拟器)和 apache pdfbox 从 pdf 文件中提取原始文本
这是我的代码。将 uri 转换为普通文件似乎有问题,因为我在“FileInputStream fis = new FileInputStream(pdf);”这一行中收到 FileNotFoundException 错误。我不是 100% 确定 uri.getPath() 是否真的为我提供了文件所需的路径。
感谢您的帮助
public class MainActivity extends AppCompatActivity {
ActivityResultLauncher<Intent> resultLauncher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
Uri uri = data.getData();
try {
readTextFromPDF(uri);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
public void chooseFile(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
resultLauncher.launch(intent);
}
private void readTextFromPDF(Uri uri) throws IOException {
File pdf = new File(uri.getPath());
FileInputStream fis = new FileInputStream(pdf);
PDDocument document = PDDocument.load(fis);
PDFTextStripper pdfTextStripper = new PDFTextStripper();
String text = pdfTextStripper.getText(document);
TextView textView = findViewById(R.id.test);
textView.setText(text);
document.close();
fis.close();
}
}
没有。 Uri.getPath() 不会为您提供文件路径。
你有一个很好的 uri,这个 uri 可以让你访问文件。
Uri.toString() 显示内容方案。
只需为获取的uri打开一个InputStream即可
其余与 FileInputStream 相同
InputStream is = getContentResolver().openInputStream(uri);