Java Code Examples for androidx.documentfile.provider.DocumentFile#createDirectory()

The following examples show how to use androidx.documentfile.provider.DocumentFile#createDirectory() . 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: DocumentUtil.java    From a with GNU General Public License v3.0 6 votes vote down vote up
public static DocumentFile createDirIfNotExist(@NonNull DocumentFile root, String... subDirs) {
    DocumentFile parent = root;
    try {
        for (String subDir1 : subDirs) {
            String subDirName = filenameFilter(Uri.decode(subDir1));
            DocumentFile subDir = parent.findFile(subDirName);
            if (subDir == null) {
                subDir = parent.createDirectory(subDirName);
            }
            parent = subDir;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return parent;
}
 
Example 2
Source File: FetchHelper.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
@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 3
Source File: DocumentUtil.java    From MyBookshelf with GNU General Public License v3.0 6 votes vote down vote up
public static DocumentFile createDirIfNotExist(@NonNull DocumentFile root, String... subDirs) {
    DocumentFile parent = root;
    try {
        for (String subDir1 : subDirs) {
            String subDirName = filenameFilter(Uri.decode(subDir1));
            DocumentFile subDir = parent.findFile(subDirName);
            if (subDir == null) {
                subDir = parent.createDirectory(subDirName);
            }
            parent = subDir;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return parent;
}
 
Example 4
Source File: DocumentUtil.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
public static DocumentFile createDirIfNotExist(DocumentFile root, String... subDirs) {
    DocumentFile parent = root;
    try {
        for (int i = 0; i < subDirs.length; i++) {
            String subDirName = filenameFilter(Uri.decode(subDirs[i]));
            DocumentFile subDir = parent.findFile(subDirName);
            if (subDir == null) {
                subDir = parent.createDirectory(subDirName);
            }
            parent = subDir;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return parent;
}
 
Example 5
Source File: FFMSettings.java    From FCM-for-Mojo with GNU General Public License v3.0 6 votes vote down vote up
public static DocumentFile getDownloadDir(Context context) {
    String uri = Settings.getString(DOWNLOADS_URI, null);
    if (uri == null) {
        return null;
    }

    DocumentFile pickedDir = DocumentFile.fromTreeUri(context, Uri.parse(uri));
    DocumentFile dir = pickedDir.findFile("FFM");

    if (dir == null)
        pickedDir = pickedDir.createDirectory("FFM");
    else
        pickedDir = dir;

    return pickedDir;
}
 
Example 6
Source File: MimiUtil.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
private static DocumentFile directoryToDocumentFile(final Context context, final String dir) {
    if (!TextUtils.isEmpty(dir)) {
        try {
            if (dir.startsWith(Utils.SCHEME_CONTENT)) {
                return DocumentFile.fromTreeUri(context, Uri.parse(dir));
            } else {
                return DocumentFile.fromFile(new File(dir));
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error creating DocumentFile from " + dir, e);
            return null;
        }
    } else {
        DocumentFile defaultDir = DocumentFile.fromFile(new File(getPicturesDirectoryAsFile(), "/Mimi"));
        if (!defaultDir.exists()) {
            DocumentFile externalStorageDir = getPicturesDirectory();
            DocumentFile mimiFolder = externalStorageDir.createDirectory("Mimi");
        }
        return defaultDir;
    }
}
 
Example 7
Source File: ImportHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: ContentHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
/**
 * Return the given site's download directory. Create it if it doesn't exist.
 *
 * @param context Context to use for the action
 * @param site    Site to get the download directory for
 * @return Download directory of the given Site
 */
@Nullable
static DocumentFile getOrCreateSiteDownloadDir(@NonNull Context context, @Nullable ContentProviderClient client, @NonNull Site site) {
    String appUriStr = Preferences.getStorageUri();
    if (appUriStr.isEmpty()) {
        Timber.e("No storage URI defined for the app");
        return null;
    }

    DocumentFile appFolder = DocumentFile.fromTreeUri(context, Uri.parse(appUriStr));
    if (null == appFolder || !appFolder.exists()) {
        Timber.e("App folder %s does not exist", appUriStr);
        return null;
    }

    String siteFolderName = site.getFolder();
    DocumentFile siteFolder;
    if (null == client)
        siteFolder = FileHelper.findFolder(context, appFolder, siteFolderName);
    else
        siteFolder = FileHelper.findFolder(context, appFolder, client, siteFolderName);

    if (null == siteFolder) // Create
        return appFolder.createDirectory(siteFolderName);
    else return siteFolder;
}
 
Example 9
Source File: SAFUtils.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 指定した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)) {
				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 10
Source File: SAFUtils.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 指定したDocumentFileが指し示すフォルダの下に指定した相対パスのディレクトリ階層を生成する
 * フォルダが存在していない時に書き込み可能でなければIOExceptionを投げる
 * deprecated #getDirを使うこと
 * @param context
 * @param baseDoc
 * @param dirs
 * @return
 * @throws IOException
 */
@Deprecated
@NonNull
public static DocumentFile getDocumentFile(
	@NonNull Context context,
	@NonNull final DocumentFile baseDoc, @Nullable final String dirs)
		throws IOException {
	
	DocumentFile tree = baseDoc;
	if (!TextUtils.isEmpty(dirs)) {
		final String[] dir = dirs.split("/");
		for (final String d: dir) {
			if (!TextUtils.isEmpty(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 11
Source File: SAFUtils.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 指定した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 12
Source File: ContentHelper.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
/**
 * Create the download directory of the given content
 *
 * @param context Context
 * @param content Content for which the directory to create
 * @return Created directory
 */
@Nullable
public static DocumentFile createContentDownloadDir(@NonNull Context context, @NonNull Content content) {
    DocumentFile siteDownloadDir = getOrCreateSiteDownloadDir(context, null, content.getSite());
    if (null == siteDownloadDir) return null;

    String bookFolderName = formatBookFolderName(content);
    DocumentFile bookFolder = FileHelper.findFolder(context, siteDownloadDir, bookFolderName);
    if (null == bookFolder) { // Create
        return siteDownloadDir.createDirectory(bookFolderName);
    } else return bookFolder;
}
 
Example 13
Source File: StorageHelper.java    From leafpicrevived with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If the file is not
 * existing, it is created.
 *
 * @param file              The file.
 * @param isDirectory       flag indicating if the file should be a directory.
 * @param createDirectories flag indicating if intermediate path directories should be created if not existing.
 * @return The DocumentFile
 */
private static DocumentFile getDocumentFile(Context context, @NonNull final File file, final boolean isDirectory, final boolean createDirectories) {

    Uri treeUri = getTreeUri(context);

    if (treeUri == null) return null;

    DocumentFile document = DocumentFile.fromTreeUri(context, treeUri);
    String sdcardPath = getSavedSdcardPath(context);
    String suffixPathPart = null;

    if (sdcardPath != null) {
        if ((file.getPath().indexOf(sdcardPath)) != -1)
            suffixPathPart = file.getAbsolutePath().substring(sdcardPath.length());
    } else {
        HashSet<File> storageRoots = StorageHelper.getStorageRoots(context);
        for (File root : storageRoots) {
            if (root != null) {
                if ((file.getPath().indexOf(root.getPath())) != -1)
                    suffixPathPart = file.getAbsolutePath().substring(file.getPath().length());
            }
        }
    }

    if (suffixPathPart == null) {
        Log.d(TAG, "unable to find the document file, filePath:" + file.getPath() + " root: " + "" + sdcardPath);
        return null;
    }

    if (suffixPathPart.startsWith(File.separator)) suffixPathPart = suffixPathPart.substring(1);

    String[] parts = suffixPathPart.split("/");

    for (int i = 0; i < parts.length; i++) { // 3 is the

        DocumentFile tmp = document.findFile(parts[i]);
        if (tmp != null)
            document = document.findFile(parts[i]);
        else {
            if (i < parts.length - 1) {
                if (createDirectories) document = document.createDirectory(parts[i]);
                else return null;
            } else if (isDirectory) document = document.createDirectory(parts[i]);
            else return document.createFile("image", parts[i]);
        }
    }

    return document;
}
 
Example 14
Source File: FolderActivity.java    From syncthing-android with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.create:
            if (TextUtils.isEmpty(mFolder.id)) {
                Toast.makeText(this, R.string.folder_id_required, Toast.LENGTH_LONG)
                        .show();
                return true;
            }
            if (TextUtils.isEmpty(mFolder.path)) {
                Toast.makeText(this, R.string.folder_path_required, Toast.LENGTH_LONG)
                        .show();
                return true;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
                mFolderUri != null) {
                /**
                 * Normally, syncthing takes care of creating the ".stfolder" marker.
                 * This fails on newer android versions if the syncthing binary only has
                 * readonly access on the path and the user tries to configure a
                 * sendonly folder. To fix this, we'll precreate the marker using java code.
                 * We also create an empty file in the marker directory, to hopefully keep
                 * it alive in the face of overzealous disk cleaner apps.
                 */
                DocumentFile dfFolder = DocumentFile.fromTreeUri(this, mFolderUri);
                if (dfFolder != null) {
                    Log.v(TAG, "Creating new directory " + mFolder.path + File.separator + FOLDER_MARKER_NAME);
                    DocumentFile marker = dfFolder.createDirectory(FOLDER_MARKER_NAME);
                    marker.createFile("text/plain", "empty");
                }
            }
            getApi().createFolder(mFolder);
            finish();
            return true;
        case R.id.remove:
            showDeleteDialog();
            return true;
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}