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

The following examples show how to use androidx.documentfile.provider.DocumentFile#createFile() . 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 vote down vote up
@NonNull
private static Request createRequest(HttpUrl base, OptionsMap global, DocumentFile ddDir, AriaFile file) throws PreparationException {
    String mime = file.getMimeType();
    String fileName = file.getName();
    if (mime == null) {
        mime = "";
    } else {
        int index = fileName.lastIndexOf('.');
        if (index != -1) fileName = fileName.substring(0, index);
    }

    DocumentFile parent = createAllDirs(ddDir, file.getRelativePath(global));
    DocumentFile dest = parent.createFile(mime, fileName);
    if (dest == null)
        throw new PreparationException("Couldn't create file inside directory: " + parent);

    return createRequest(file.getDownloadUrl(global, base), dest.getUri());
}
 
Example 2
Source File: LocalBackupUtils.java    From SAI with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("DefaultLocale")
@Nullable
private static Uri createBackupUriViaSaf(Context c, Uri backupDirUri, PackageMeta packageMeta, String extension) {
    DocumentFile backupDirFile = DocumentFile.fromTreeUri(c, backupDirUri);
    if (backupDirFile == null)
        return null;

    String backupFileName = getFileNameForPackageMeta(c, packageMeta);

    String actualBackupFileName = String.format("%s.%s", backupFileName, extension);
    int suffix = 0;
    while (true) {
        DocumentFile backupFileCandidate = DocumentFile.fromSingleUri(c, SafUtils.buildChildDocumentUri(backupDirUri, actualBackupFileName));
        if (backupFileCandidate == null || !backupFileCandidate.exists())
            break;

        actualBackupFileName = String.format("%s(%d).%s", backupFileName, ++suffix, extension);
    }

    DocumentFile backupFile = backupDirFile.createFile("saf/sucks", FileUtils.buildValidFatFilename(actualBackupFileName));
    if (backupFile == null)
        return null;

    return backupFile.getUri();
}
 
Example 3
Source File: SAFUtils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 指定したDocumentFileの下にファイルを生成する
 * dirsがnullまたは空文字列ならDocumentFile#createFileを呼ぶのと同じ
 * @param parent
 * @param dirs
 * @param mime
 * @param name
 * @return
 * @throws IOException
 */
@NonNull
public static DocumentFile getFile(
	@NonNull final DocumentFile parent,
	@Nullable final String dirs,
	@NonNull final String mime,
	@NonNull final String name) throws IOException {
	
	final DocumentFile tree = getDir(parent, dirs);
	final DocumentFile file = tree.findFile(name);
	if (file != null) {
		if (file.isFile()) {
			return file;
		} else {
			throw new IOException("directory with same name already exists");
		}
	} else {
		return tree.createFile(mime, name);
	}
}
 
Example 4
Source File: SAFUtils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 指定した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 5
Source File: SAFUtils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 指定したidに対応するUriが存在する時にその下に生成したファイルのrawファイルディスクリプタを返す
 * @param context
 * @param treeUri
 * @param mime
 * @param fileName
 * @return
 * @throws UnsupportedOperationException
 * @throws FileNotFoundException
 * @throws IOException
 */
@Deprecated
public static int createStorageFileFD(
	@NonNull final Context context,
	final Uri treeUri, final String mime, final String fileName)
		throws IOException, UnsupportedOperationException {

	if (DEBUG) Log.v(TAG, "createStorageFileFD:" + fileName);
	if (BuildCheck.isLollipop()) {
		if ((treeUri != null) && !TextUtils.isEmpty(fileName)) {
			final DocumentFile saveTree = DocumentFile.fromTreeUri(context, treeUri);
			final DocumentFile target = saveTree.createFile(mime, fileName);
			try {
				final ParcelFileDescriptor fd
					= context.getContentResolver().openFileDescriptor(target.getUri(), "rw");
				return fd != null ? fd.getFd() : 0;
			} catch (final FileNotFoundException e) {
				Log.w(TAG, e);
			}
		}
		throw new FileNotFoundException();
	} else {
		throw new UnsupportedOperationException("should be API>=21");
	}
}
 
Example 6
Source File: SAFUtils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 指定したDocumentFileの下にファイルを生成する
 * dirsがnullまたは空文字列ならDocumentFile#createFileを呼ぶのと同じ
 * @param parent
 * @param dirs
 * @param mime
 * @param name
 * @return
 * @throws IOException
 */
@NonNull
public static DocumentFile getFile(
	@NonNull final DocumentFile parent,
	@Nullable final String dirs,
	@NonNull final String mime,
	@NonNull final String name) throws IOException {
	
	final DocumentFile tree = getDir(parent, dirs);
	final DocumentFile file = tree.findFile(name);
	if (file != null) {
		if (file.isFile()) {
			return file;
		} else {
			throw new IOException("directory with same name already exists");
		}
	} else {
		return tree.createFile(mime, name);
	}
}
 
Example 7
Source File: FileHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
public static boolean checkAndSetRootFolder(@NonNull final Context context, @NonNull final DocumentFile folder, boolean notify) {
    // Validate folder
    if (!folder.exists() && !folder.isDirectory()) {
        if (notify)
            ToastUtil.toast(context, R.string.error_creating_folder);
        return false;
    }

    // Remove and add back the nomedia file to test if the user has the I/O rights to the selected folder
    DocumentFile nomedia = findFile(context, folder, NOMEDIA_FILE_NAME);
    if (nomedia != null) nomedia.delete();

    nomedia = folder.createFile("application/octet-steam", NOMEDIA_FILE_NAME);
    if (null != nomedia && nomedia.exists()) {
        boolean deleted = nomedia.delete();
        if (deleted) Timber.d(".nomedia file deleted");
    } else {
        if (notify)
            ToastUtil.toast(context, R.string.error_write_permission);
        return false;
    }

    Preferences.setStorageUri(folder.getUri().toString());
    return true;
}
 
Example 8
Source File: Utils.java    From ProjectX with Apache License 2.0 6 votes vote down vote up
/**
 * 创建文件
 *
 * @param dir  目录
 * @param name 文件名
 * @return 创建的文件,失败时返回null
 */
static DocumentFile createNewFile(final DocumentFile dir, String name) {
    for (int i = 0; i < 5; i++) {
        final DocumentFile file = dir.createFile(MIME,
                BASE_NAME + System.currentTimeMillis());
        if (file != null) {
            // 创建成功
            if (file.renameTo(name))
                return file;
            else {
                // 重命名失败,删除并返回
                file.delete();
                return null;
            }
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            // ignore
        }
    }
    return null;
}
 
Example 9
Source File: DocumentUtil.java    From a with GNU General Public License v3.0 5 votes vote down vote up
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 10
Source File: DocumentUtil.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
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 11
Source File: DocumentUtil.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
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 12
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 13
Source File: RecordingService.java    From libcommon with Apache License 2.0 4 votes vote down vote up
/**
	 * #startの実態, mSyncをロックして呼ばれる
	 * @param outputDir 出力ディレクトリ
	 * @param name 出力ファイル名(拡張子なし)
	 * @param videoFormat
	 * @param audioFormat
	 * @throws IOException
	 */
	@SuppressLint("NewApi")
	protected void internalStart(
		@NonNull final DocumentFile outputDir,
		@NonNull final String name,
		@Nullable final MediaFormat videoFormat,
		@Nullable final MediaFormat audioFormat) throws IOException {

		if (DEBUG) Log.v(TAG, "internalStart:");
		final DocumentFile output = outputDir.createFile("*/*", name + ".mp4");
		IMuxer muxer = null;
		if (BuildCheck.isOreo()) {
			if (USE_MEDIASTORE_OUTPUT_STREAM) {
				if (DEBUG) Log.v(TAG, "internalStart:create MediaMuxerWrapper using MediaStoreOutputStream");
				muxer = new MediaMuxerWrapper(
//					new MediaStoreOutputStream(this, "*/mp4", null, output.getName(), UriHelper.getPath(this, output.getUri())),
					new MediaStoreOutputStream(this, "video/mp4", Environment.DIRECTORY_MOVIES + "/" + Const.APP_DIR, output.getName()),
					MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
			} else {
				if (DEBUG) Log.v(TAG, "internalStart:create MediaMuxerWrapper using ContentResolver");
				muxer = new MediaMuxerWrapper(getContentResolver()
					.openFileDescriptor(output.getUri(), "rw").getFileDescriptor(),
					MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
			}
		} else {
			if (DEBUG) Log.v(TAG, "internalStart:create MediaMuxerWrapper using File");
			final String path = UriHelper.getPath(this, output.getUri());
			final File f = new File(UriHelper.getPath(this, output.getUri()));
			if (/*!f.exists() &&*/ f.canWrite()) {
				// 書き込めるファイルパスを取得できればそれを使う
				muxer = new MediaMuxerWrapper(path,
					MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
			} else {
				Log.w(TAG, "cant't write to the file, try to use VideoMuxer instead");
			}
		}
		if (muxer == null) {
			throw new IllegalArgumentException();
		}
		mMuxer = muxer;
		mVideoTrackIx = videoFormat != null ? muxer.addTrack(videoFormat) : -1;
		mAudioTrackIx = audioFormat != null ? muxer.addTrack(audioFormat) : -1;
		mMuxer.start();
		synchronized (mSync) {
			mSync.notifyAll();
		}
	}
 
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);
    }
}
 
Example 15
Source File: FileHelper.java    From Hentoid with Apache License 2.0 3 votes vote down vote up
/**
 * Return the DocumentFile with the given display name located in the given folder
 * If it doesn't exist, create a new one and return it
 *
 * @param context     Context to use
 * @param folder      Containing folder
 * @param mimeType    Mime-type to use if the document has to be created
 * @param displayName Display name of the document
 * @return Usable DocumentFile; null if creation failed
 */
@Nullable
public static DocumentFile findOrCreateDocumentFile(@NonNull final Context context, @NonNull final DocumentFile folder, @Nullable String mimeType, @NonNull final String displayName) {
    // Look for it first
    DocumentFile file = findFile(context, folder, displayName);
    if (null == file) { // Create it
        if (null == mimeType) mimeType = "application/octet-steam";
        return folder.createFile(mimeType, displayName);
    } else return file;
}