直接ファイルを操作しようとすると止められるので次の工程を取る
- Storage Access Frameworkを利用してファイルを選択
- 内部ストレージ ディレクトリにファイルを保存
- 内部ファイルに対して処理をする
- EPUBファイルを出力
- Storage Access Frameworkを利用してファイルを保存
findViewById(R.id.button).setOnClickListener(v -> { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); String[] mimeTypes ={ "text/plain", "application/zip"}; intent.setType("*/*").putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes); Intent chooserIntent = Intent.createChooser(intent, "ファイルの選択"); _launcherSelectFile.launch(chooserIntent); });
ActivityResultLauncher<Intent> _launcherSelectFile = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { Charset cs; if (result.getResultCode() == RESULT_OK) { Intent resultData = result.getData(); if (resultData != null) { Uri uri = resultData.getData(); String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME}; String path = null; Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(0); } cursor.close(); Context context = getApplicationContext(); file = new File(context.getFilesDir(), path); System.out.println("filename:" + path); System.out.println("filename:" + file.getPath()); } try { InputStream inputStream = getContentResolver().openInputStream(uri); cs= Charset.forName(Detector.getCharset(inputStream)); System.out.println("charset:" + cs); inputStream = getContentResolver().openInputStream(uri); Files.copy(inputStream, file.toPath()); } catch (IOException e) { e.printStackTrace(); } } } });
ファイルをコピーするだけ使うために android sdk 30以上に変えた
Using Files#copy(InputStream,Path,CopyOption...) public static void copyUrlToFile(URL url, Path file) throws IOException { try (InputStream input = url.openStream()) { Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING); } } stackoverflow.com
uriからファイル名の取得