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

The following examples show how to use androidx.documentfile.provider.DocumentFile#delete() . 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: ContentHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the given Content from the disk and the DB
 *
 * @param content Content to be removed
 * @param dao     DAO to be used
 */
public static void removeContent(@NonNull Context context, @NonNull Content content, @NonNull CollectionDAO dao) {
    Helper.assertNonUiThread();
    // Remove from DB
    // NB : start with DB to have a LiveData feedback, because file removal can take much time
    dao.deleteContent(content);
    // If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete
    if (!content.getStorageUri().isEmpty()) {
        DocumentFile folder = DocumentFile.fromTreeUri(context, Uri.parse(content.getStorageUri()));
        if (null == folder || !folder.exists()) return;

        if (folder.delete()) {
            Timber.i("Directory removed : %s", content.getStorageUri());
        } else {
            Timber.w("Failed to delete directory : %s", content.getStorageUri()); // TODO use exception to display feedback on screen
        }
    }
}
 
Example 2
Source File: ContentHelper.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the given page from the disk and the DB
 *
 * @param image Page to be removed
 * @param dao   DAO to be used
 */
public static void removePage(@NonNull ImageFile image, @NonNull CollectionDAO dao, @NonNull final Context context) {
    Helper.assertNonUiThread();
    // Remove from DB
    // NB : start with DB to have a LiveData feedback, because file removal can take much time
    dao.deleteImageFile(image);

    // Remove the page from disk
    if (image.getFileUri() != null && !image.getFileUri().isEmpty()) {
        Uri uri = Uri.parse(image.getFileUri());

        DocumentFile doc = DocumentFile.fromSingleUri(context, uri);
        if (doc != null && doc.exists()) doc.delete();
    }

    // Update content JSON if it exists (i.e. if book is not queued)
    Content content = dao.selectContent(image.content.getTargetId());
    if (!content.getJsonUri().isEmpty()) updateJson(context, content);
}
 
Example 3
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 4
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 5
Source File: DocumentUtil.java    From a with GNU General Public License v3.0 5 votes vote down vote up
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 6
Source File: LocalBackupStorage.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void deleteFile(Uri uri) {
    uri = deNamespaceUri(uri);
    DocumentFile docFile = SafUtils.docFileFromSingleUriOrFileUri(mContext, uri);
    if (docFile != null)
        docFile.delete();
}
 
Example 7
Source File: LocalBackupStorage.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void deleteBackup(Uri backupUri) {
    backupUri = deNamespaceUri(backupUri);
    DocumentFile docFile = SafUtils.docFileFromSingleUriOrFileUri(mContext, backupUri);
    if (docFile == null)
        return;

    if (!docFile.exists()) {
        notifyBackupRemoved(namespaceUri(backupUri));
    } else if (docFile.delete()) {
        notifyBackupRemoved(namespaceUri(backupUri));
    }
}
 
Example 8
Source File: DocumentUtil.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
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 9
Source File: DocumentUtil.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
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 10
Source File: DCCTransferListAdapter.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
private void delete() {
    if (mFileUri != null && mFileUri.length() > 0) {
        Uri uri = Uri.parse(mFileUri);
        DocumentFile file;
        if (uri.getScheme().equals("file"))
            file = DocumentFile.fromFile(new File(uri.getPath()));
        else
            file = DocumentFile.fromSingleUri(itemView.getContext(), uri);
        if (file.exists())
            file.delete();
    }
    DCCManager.getInstance(itemView.getContext()).getHistory().removeEntry(mEntryId);
}
 
Example 11
Source File: FileUtil.java    From Augendiagnose with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Delete a file. May be even on external SD card.
 *
 * @param file the file to be deleted.
 * @return True if successfully deleted.
 */
public static boolean deleteFile(@NonNull final File file) {
	// First try the normal deletion.
	if (file.delete()) {
		return true;
	}

	// Try with Storage Access Framework.
	if (SystemUtil.isAndroid5()) {
		DocumentFile document = getDocumentFile(file, false, true);
		return document != null && document.delete();
	}

	// Try the Kitkat workaround.
	if (SystemUtil.isKitkat()) {
		ContentResolver resolver = Application.getAppContext().getContentResolver();

		try {
			Uri uri = MediaStoreUtil.getUriFromFile(file.getAbsolutePath());
			if (uri != null) {
				resolver.delete(uri, null, null);
			}
			return !file.exists();
		}
		catch (Exception e) {
			Log.e(Application.TAG, "Error when deleting file " + file.getAbsolutePath(), e);
			return false;
		}
	}

	return !file.exists();
}
 
Example 12
Source File: FileUtil.java    From Augendiagnose with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Delete a folder.
 *
 * @param file The folder name.
 * @return true if successful.
 */
public static boolean rmdir(@NonNull final File file) {
	if (!file.exists()) {
		return true;
	}
	if (!file.isDirectory()) {
		return false;
	}
	String[] fileList = file.list();
	if (fileList != null && fileList.length > 0) {
		// Delete only empty folder.
		return false;
	}

	// Try the normal way
	if (file.delete()) {
		return true;
	}

	// Try with Storage Access Framework.
	if (SystemUtil.isAndroid5()) {
		DocumentFile document = getDocumentFile(file, true, true);
		return document != null && document.delete();
	}

	// Try the Kitkat workaround.
	if (SystemUtil.isKitkat()) {
		ContentResolver resolver = Application.getAppContext().getContentResolver();
		ContentValues values = new ContentValues();
		values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
		resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

		// Delete the created entry, such that content provider will delete the file.
		resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?",
				new String[]{file.getAbsolutePath()});
	}

	return !file.exists();
}
 
Example 13
Source File: StorageHelper.java    From leafpicrevived with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Delete a folder.
 *
 * @param file The folder name.
 * @return true if successful.
 */
public static boolean rmdir(Context context, @NonNull final File file) {

    if (!file.exists() && !file.isDirectory()) return false;

    String[] fileList = file.list();

    if (fileList != null && fileList.length > 0)
        // Delete only empty folder.
        return false;

    // Try the normal way
    if (file.delete()) return true;


    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(context, file, true, true);
        return document != null && document.delete();
    }

    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        // Delete the created entry, such that content provider will delete the file.
        resolver.delete(MediaStore.Files.getContentUri("external"), MediaStore.MediaColumns.DATA + "=?",
                new String[]{file.getAbsolutePath()});
    }

    return !file.exists();
}