androidx.documentfile.provider.DocumentFile Java Examples
The following examples show how to use
androidx.documentfile.provider.DocumentFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FetchHelper.java From Aria2App with GNU General Public License v3.0 | 6 votes |
@NonNull private static DocumentFile createAllDirs(@NonNull DocumentFile parent, @NonNull String filePath) throws PreparationException { String[] split = filePath.split(Pattern.quote(File.separator)); for (int i = 0; i < split.length - 1; i++) { // Skip last segment DocumentFile doc = parent.findFile(split[i]); if (doc == null || !doc.isDirectory()) { parent = parent.createDirectory(split[i]); if (parent == null) throw new PreparationException("Couldn't create directory: " + split[i]); } else { parent = doc; } } return parent; }
Example #2
Source File: LogUtil.java From Hentoid with Apache License 2.0 | 6 votes |
@Nullable public static DocumentFile writeLog(@Nonnull Context context, @Nonnull LogInfo info) { // Create the log String log = buildLog(info); String logFileName = info.fileName + ".txt"; // Save it try { String settingFolderUriStr = Preferences.getStorageUri(); if (settingFolderUriStr.isEmpty()) return null; DocumentFile folder = DocumentFile.fromTreeUri(context, Uri.parse(settingFolderUriStr)); if (null == folder || !folder.exists()) return null; DocumentFile logDocumentFile = FileHelper.findOrCreateDocumentFile(context, folder, "text/plain", logFileName); FileHelper.saveBinaryInFile(context, logDocumentFile, log.getBytes()); return logDocumentFile; } catch (Exception e) { Timber.e(e); } return null; }
Example #3
Source File: ContentHelper.java From Hentoid with Apache License 2.0 | 6 votes |
/** * Find the picture files for the given Content * NB1 : Pictures with non-supported formats are not included in the results * NB2 : Cover picture is not included in the results * * @param content Content to retrieve picture files for * @return List of picture files */ public static List<DocumentFile> getPictureFilesFromContent(@NonNull final Context context, @NonNull final Content content) { Helper.assertNonUiThread(); String storageUri = content.getStorageUri(); Timber.d("Opening: %s from: %s", content.getTitle(), storageUri); DocumentFile folder = DocumentFile.fromTreeUri(context, Uri.parse(storageUri)); if (null == folder || !folder.exists()) { Timber.d("File not found!! Exiting method."); return new ArrayList<>(); } return FileHelper.listFoldersFilter(context, folder, displayName -> (displayName.toLowerCase().startsWith(Consts.THUMB_FILE_NAME) && Helper.isImageExtensionSupported(FileHelper.getExtension(displayName)) ) ); }
Example #4
Source File: SAFUtils.java From libcommon with Apache License 2.0 | 6 votes |
/** * 指定したUriがDocumentFileの下に存在するフォルダを指し示していれば * 対応するDocumentFileを取得して返す * フォルダが存在していない時に書き込み可能でなければIOExceptionを投げる * @param context * @param baseDoc * @param uri * @return * @throws FileNotFoundException * @throws IOException */ @Deprecated @NonNull public static DocumentFile getDocumentFile( @NonNull Context context, @NonNull final DocumentFile baseDoc, @NonNull final Uri uri) throws IOException { final String basePathString = UriHelper.getPath(context, baseDoc.getUri()); final String uriString = UriHelper.getPath(context, uri); if (!TextUtils.isEmpty(basePathString) && !TextUtils.isEmpty(uriString) && uriString.startsWith(basePathString)) { return getDir(baseDoc, uriString.substring(basePathString.length())); } throw new FileNotFoundException(); }
Example #5
Source File: BookSourcePresenter.java From a with GNU General Public License v3.0 | 6 votes |
@Override public void importBookSourceLocal(String path) { if (TextUtils.isEmpty(path)) { mView.toast(R.string.read_file_error); return; } String json; DocumentFile file; try { file = DocumentFile.fromFile(new File(path)); } catch (Exception e) { mView.toast(path + "无法打开!"); return; } json = DocumentHelper.readString(file); if (!isEmpty(json)) { mView.showSnackBar("正在导入书源", Snackbar.LENGTH_INDEFINITE); importBookSource(json); } else { mView.toast(R.string.read_file_error); } }
Example #6
Source File: ImportHelper.java From Hentoid with Apache License 2.0 | 6 votes |
@Nullable private static DocumentFile addHentoidFolder(@NonNull final Context context, @NonNull final DocumentFile baseFolder) { String folderName = baseFolder.getName(); if (null == folderName) folderName = ""; // Don't create a .Hentoid subfolder inside the .Hentoid (or Hentoid) folder the user just selected... if (!isHentoidFolderName(folderName)) { DocumentFile targetFolder = getExistingHentoidDirFrom(context, baseFolder); // If not, create one if (targetFolder.getUri().equals(baseFolder.getUri())) return targetFolder.createDirectory(Consts.DEFAULT_LOCAL_DIRECTORY); else return targetFolder; } return baseFolder; }
Example #7
Source File: SAFUtils.java From libcommon with Apache License 2.0 | 6 votes |
/** * 指定したUriが存在する時にその下にファイルを生成するためのpathを返す * @param context * @param treeUri * @param mime * @param fileName * @return * @throws UnsupportedOperationException * @throws FileNotFoundException * @throws IOException */ @Deprecated @NonNull public static File createStorageFile( @NonNull final Context context, final Uri treeUri, final String mime, final String fileName) throws IOException { if (DEBUG) Log.v(TAG, "createStorageFile:" + fileName); if (BuildCheck.isLollipop()) { if ((treeUri != null) && !TextUtils.isEmpty(fileName)) { final DocumentFile saveTree = DocumentFile.fromTreeUri(context, treeUri); final DocumentFile target = saveTree.createFile(mime, fileName); final String path = UriHelper.getPath(context, target.getUri()); if (!TextUtils.isEmpty(path)) { return new File(path); } } throw new FileNotFoundException(); } else { throw new UnsupportedOperationException("should be API>=21"); } }
Example #8
Source File: ZipUtil.java From Hentoid with Apache License 2.0 | 6 votes |
private static void addFile(@NonNull final Context context, @NonNull final DocumentFile file, final ZipOutputStream stream, final byte[] data) throws IOException { Timber.d("Adding: %s", file); try (InputStream fi = FileHelper.getInputStream(context, file); BufferedInputStream origin = new BufferedInputStream(fi, BUFFER)) { ZipEntry zipEntry = new ZipEntry(file.getName()); stream.putNextEntry(zipEntry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { stream.write(data, 0, count); } } }
Example #9
Source File: DocumentTreeRecyclerAdapter.java From libcommon with Apache License 2.0 | 6 votes |
/** * コンストラクタ * @param context * @param layoutResId * @param root ディレクトリを示すDocumentFile */ public DocumentTreeRecyclerAdapter( @NonNull final Context context, @LayoutRes final int layoutResId, @NonNull final DocumentFile root) { super(); if (root == null || !root.isDirectory()) { throw new IllegalArgumentException("root should be a directory!"); } mContext = context; mLayoutRes = layoutResId; mRoot = root; mAsyncHandler = HandlerThreadHandler.createHandler(TAG); internalChangeDir(root); }
Example #10
Source File: ImportService.java From Hentoid with Apache License 2.0 | 6 votes |
@CheckResult private Content importJsonV2(@NonNull final DocumentFile json, @NonNull final DocumentFile parentFolder) throws ParseException { try { JsonContent content = JsonHelper.jsonToObject(this, json, JsonContent.class); Content result = content.toEntity(); result.setJsonUri(json.getUri().toString()); result.setStorageUri(parentFolder.getUri().toString()); if (result.getStatus() != StatusContent.DOWNLOADED && result.getStatus() != StatusContent.ERROR) { result.setStatus(StatusContent.MIGRATED); } return result; } catch (Exception e) { Timber.e(e, "Error reading JSON (v2) file"); throw new ParseException("Error reading JSON (v2) file : " + e.getMessage(), e); } }
Example #11
Source File: SAFUtils.java From libcommon with Apache License 2.0 | 6 votes |
/** * 指定したディレクトリ配下に存在するファイルの一覧を取得 * @param dir * @param filter nullなら存在するファイルを全て追加 * @return */ @NonNull public static List<DocumentFile> listFiles( @NonNull final DocumentFile dir, @Nullable final FileFilter filter) { final List<DocumentFile> result = new ArrayList<DocumentFile>(); if (dir.isDirectory()) { final DocumentFile[] files = dir.listFiles(); for (final DocumentFile file: files) { if ((filter == null) || (filter.accept(file))) { result.add(file); } } } return result; }
Example #12
Source File: SAFUtils.java From libcommon with Apache License 2.0 | 5 votes |
/** * 指定したDocumentFileが書き込み可能であればその下にディレクトリを生成して * そのディレクトリを示すDocumentFileオブジェクトを返す * @param parent * @param dirs * @return * @throws IOException */ @NonNull public static DocumentFile getDir( @NonNull final DocumentFile parent, @Nullable final String dirs) throws IOException { DocumentFile tree = parent; if (!TextUtils.isEmpty(dirs)) { final String[] dir = dirs.split("/"); for (final String d: dir) { if (!TextUtils.isEmpty(d)) { if ("..".equals(d)) { tree = tree.getParentFile(); if (tree == null) { throw new IOException("failed to get parent directory"); } } else if (!".".equals(d)) { final DocumentFile t = tree.findFile(d); if ((t != null) && t.isDirectory()) { // 既に存在している時は何もしない tree = t; } else if (t == null) { if (tree.canWrite()) { // 存在しないときはディレクトリを生成 tree = tree.createDirectory(d); } else { throw new IOException("can't create directory"); } } else { throw new IOException("can't create directory, file with same name already exists"); } } } } } return tree; }
Example #13
Source File: DocumentUtil.java From MyBookshelf with GNU General Public License v3.0 | 5 votes |
public static DocumentFile createFileIfNotExist(Context context, String mimeType, String fileName, Uri rootUri, String... subDirs) { DocumentFile parent = createDirIfNotExist(context, rootUri, subDirs); if (parent == null) return null; fileName = filenameFilter(Uri.decode(fileName)); DocumentFile file = parent.findFile(fileName); if (file == null) { file = parent.createFile(mimeType, fileName); } return file; }
Example #14
Source File: DocumentTreeRecyclerAdapter.java From libcommon with Apache License 2.0 | 5 votes |
/** * ディレクトリ切り替え実行 * @param newDir */ private void internalChangeDir(@NonNull final DocumentFile newDir) { if (DEBUG) Log.v(TAG, "internalChangeDir:" + newDir); synchronized (mSync) { if (mAsyncHandler != null) { mAsyncHandler.post(new ChangeDirTask(newDir)); } else { throw new IllegalStateException("already released"); } } }
Example #15
Source File: DocumentUtil.java From MyBookshelf with GNU General Public License v3.0 | 5 votes |
public static boolean deleteFile(String fileName, DocumentFile root, String... subDirs) { DocumentFile parent = getDirDocument(root, subDirs); if (parent == null) return false; fileName = filenameFilter(Uri.decode(fileName)); DocumentFile file = parent.findFile(fileName); return file != null && file.exists() && file.delete(); }
Example #16
Source File: SafUtils.java From SAI with GNU General Public License v3.0 | 5 votes |
@Nullable public static String getFileNameFromContentUri(Context context, Uri contentUri) { DocumentFile documentFile = docFileFromSingleUriOrFileUri(context, contentUri); if (documentFile == null) return null; return documentFile.getName(); }
Example #17
Source File: DocumentUtil.java From HaoReader with GNU General Public License v3.0 | 5 votes |
public static InputStream getFileInputSteam(Context context, String fileName, DocumentFile root, String... subDirs) { DocumentFile parent = getDirDocument(root, subDirs); if (parent == null) return null; DocumentFile file = parent.findFile(fileName); if (file == null) return null; return getFileInputSteam(context, file.getUri()); }
Example #18
Source File: ErrorsDialogFragment.java From Hentoid with Apache License 2.0 | 5 votes |
private void showErrorLog(@NonNull final Content content) { ToastUtil.toast(R.string.redownload_generating_log_file); LogUtil.LogInfo logInfo = createLog(content); DocumentFile logFile = LogUtil.writeLog(requireContext(), logInfo); if (logFile != null) FileHelper.openFile(requireContext(), logFile); }
Example #19
Source File: DocumentTreeRecyclerAdapter.java From libcommon with Apache License 2.0 | 5 votes |
/** * 指定したディレクトリへ切り替え * コンストラクタのroot引数で指定したディレクトリorその下位ディレクトリを指定すること * @param newDir * @throws IOException */ public void changeDir(@NonNull final DocumentFile newDir) throws IOException { if (DEBUG) Log.v(TAG, "changeDir:newDir=" + newDir.getUri()); if (newDir.isDirectory()) { internalChangeDir(newDir); notifyDataSetChanged(); } else { throw new IOException(String.format(Locale.US, "%s is not a directory/could not read", newDir.getUri())); } }
Example #20
Source File: DocumentTreeRecyclerAdapter.java From libcommon with Apache License 2.0 | 5 votes |
@Override public void run() { if (DEBUG) Log.v(TAG, "ChangeDirTask#run:"); mWork.clear(); // ファイルリストを更新 final Collection<DocumentFile> fileList = SAFUtils.listFiles(newDir, mFileFilter); if (DEBUG) Log.v(TAG, "ChangeDirTask#run:" + fileList); for (final DocumentFile file : fileList) { mWork.add(new FileInfo(file, false)); } Collections.sort(mWork); // 親フォルダに戻るパスの追加 if (!mRoot.equals(newDir)) { if (DEBUG) Log.v(TAG, "ChangeDirTask#run:check up navigation"); final DocumentFile parent = newDir.getParentFile(); if (parent != null) { // add at top if (DEBUG) Log.v(TAG, "ChangeDirTask#run:add up navigation at top"); mWork.add(0, new FileInfo(parent, true)); } } mUIHandler.postDelayed(new Runnable() { @Override public void run() { synchronized (mItems) { mCurrentDir = newDir; mItems.clear(); mItems.addAll(mWork); } mWork.clear(); notifyDataSetChanged(); } }, DELAY_MILLIS); }
Example #21
Source File: DocumentUtil.java From MyBookshelf with GNU General Public License v3.0 | 5 votes |
public static boolean writeBytes(Context context, byte[] data, String fileName, Uri rootUri, String... subDirs) { DocumentFile parent = getDirDocument(context, rootUri, subDirs); if (parent == null) return false; fileName = filenameFilter(Uri.decode(fileName)); DocumentFile file = parent.findFile(fileName); return writeBytes(context, data, file.getUri()); }
Example #22
Source File: DocumentUtil.java From a with GNU General Public License v3.0 | 5 votes |
public static InputStream getFileInputSteam(Context context, String fileName, DocumentFile root, String... subDirs) { DocumentFile parent = getDirDocument(root, subDirs); if (parent == null) return null; DocumentFile file = parent.findFile(fileName); if (file == null) return null; return getFileInputSteam(context, file.getUri()); }
Example #23
Source File: ContentDownloadService.java From Hentoid with Apache License 2.0 | 5 votes |
private void onRequestError(VolleyError error, @NonNull ImageFile img, @NonNull DocumentFile dir, @NonNull String backupUrl) { // Try with the backup URL, if it exists and if the current image isn't a backup itself if (!img.isBackup() && !backupUrl.isEmpty()) { tryUsingBackupUrl(img, dir, backupUrl); return; } // If no backup, then process the error String statusCode = (error.networkResponse != null) ? error.networkResponse.statusCode + "" : "N/A"; String message = error.getMessage() + (img.isBackup() ? " (from backup URL)" : ""); String cause = ""; if (error instanceof TimeoutError) { cause = "Timeout"; } else if (error instanceof NoConnectionError) { cause = "No connection"; } else if (error instanceof AuthFailureError) { // 403's fall in this category cause = "Auth failure"; } else if (error instanceof ServerError) { // 404's fall in this category cause = "Server error"; } else if (error instanceof NetworkError) { cause = "Network error"; } else if (error instanceof ParseError) { cause = "Network parse error"; } Timber.w(error); updateImageStatusUri(img, false, ""); logErrorRecord(img.content.getTargetId(), ErrorType.NETWORKING, img.getUrl(), img.getName(), cause + "; HTTP statusCode=" + statusCode + "; message=" + message); }
Example #24
Source File: DocumentUtil.java From HaoReader with GNU General Public License v3.0 | 5 votes |
public static DocumentFile getDirDocument(DocumentFile root, String... subDirs) { DocumentFile parent = root; for (int i = 0; i < subDirs.length; i++) { String subDirName = Uri.decode(subDirs[i]); DocumentFile subDir = parent.findFile(subDirName); if (subDir != null) parent = subDir; else return null; } return parent; }
Example #25
Source File: DocumentUtil.java From a with GNU General Public License v3.0 | 5 votes |
public static OutputStream getFileOutputSteam(Context context, String fileName, String rootPath, String... subDirs) { DocumentFile parent = getDirDocument(context, rootPath, subDirs); if (parent == null) return null; DocumentFile file = parent.findFile(fileName); if (file == null) return null; return getFileOutputSteam(context, file.getUri()); }
Example #26
Source File: DocumentUtil.java From HaoReader with GNU General Public License v3.0 | 5 votes |
public static boolean writeBytes(Context context, byte[] data, String fileName, String rootPath, String... subDirs) { DocumentFile parent = getDirDocument(context, rootPath, subDirs); if (parent == null) return false; DocumentFile file = parent.findFile(fileName); return writeBytes(context, data, file.getUri()); }
Example #27
Source File: DocumentUtil.java From HaoReader with GNU General Public License v3.0 | 5 votes |
public static DocumentFile createDirIfNotExist(Context context, String rootPath, String... subDirs) { Uri rootUri; if (rootPath.startsWith("content")) rootUri = Uri.parse(rootPath); else rootUri = Uri.parse(Uri.decode(rootPath)); return createDirIfNotExist(context, rootUri, subDirs); }
Example #28
Source File: DocumentUtil.java From a with GNU General Public License v3.0 | 5 votes |
public static DocumentFile getDirDocument(Context context, String rootPath, String... subDirs) { Uri rootUri; if (rootPath.startsWith("content")) rootUri = Uri.parse(rootPath); else rootUri = Uri.parse(Uri.decode(rootPath)); return getDirDocument(context, rootUri, subDirs); }
Example #29
Source File: FileUtil.java From Hentoid with Apache License 2.0 | 5 votes |
static List<DocumentFile> listDocumentFiles( @NonNull final Context context, @NonNull final DocumentFile parent, @NonNull final ContentProviderClient client, final FileHelper.NameFilter nameFilter, boolean listFolders, boolean listFiles) { final List<ImmutableTriple<Uri, String, Long>> results = new ArrayList<>(); final Uri searchUri = DocumentsContract.buildChildDocumentsUriUsingTree(parent.getUri(), DocumentsContract.getDocumentId(parent.getUri())); try (Cursor c = client.query(searchUri, new String[]{ DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE}, null, null, null)) { if (c != null) while (c.moveToNext()) { final String documentId = c.getString(0); final String documentName = c.getString(1); boolean isFolder = c.getString(2).equals(DocumentsContract.Document.MIME_TYPE_DIR); final Long documentSize = c.getLong(3); // FileProvider doesn't take query selection arguments into account, so the selection has to be done manually if ((null == nameFilter || nameFilter.accept(documentName)) && ((listFiles && !isFolder) || (listFolders && isFolder))) results.add(new ImmutableTriple<>(DocumentsContract.buildDocumentUriUsingTree(parent.getUri(), documentId), documentName, documentSize)); } } catch (Exception e) { Timber.w(e, "Failed query"); } return convertFromUris(context, results); }
Example #30
Source File: DocumentUtil.java From a with GNU General Public License v3.0 | 5 votes |
public static byte[] readBytes(Context context, String fileName, DocumentFile root, String... subDirs) { DocumentFile parent = getDirDocument(root, subDirs); if (parent == null) return null; fileName = filenameFilter(Uri.decode(fileName)); DocumentFile file = parent.findFile(fileName); if (file == null) return null; return readBytes(context, file.getUri()); }