Java Code Examples for android.support.v4.provider.DocumentFile#exists()

The following examples show how to use android.support.v4.provider.DocumentFile#exists() . 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: Copy.java    From Camera-Roll-Android-App with Apache License 2.0 6 votes vote down vote up
static boolean copyFileOntoRemovableStorage(Context context, Uri treeUri,
                                            String path, String destination) throws IOException {
    String mimeType = MediaType.getMimeType(path);
    DocumentFile file = DocumentFile.fromFile(new File(destination));
    if (file.exists()) {
        int index = destination.lastIndexOf(".");
        destination = destination.substring(0, index) + " Copy"
                + destination.substring(index, destination.length());
    }
    DocumentFile destinationFile = StorageUtil.createDocumentFile(context, treeUri, destination, mimeType);

    if (destinationFile != null) {
        ContentResolver resolver = context.getContentResolver();
        OutputStream outputStream = resolver.openOutputStream(destinationFile.getUri());
        InputStream inputStream = new FileInputStream(path);
        return writeStream(inputStream, outputStream);
    }
    return false;
}
 
Example 2
Source File: FileUtil.java    From FileManager with Apache License 2.0 6 votes vote down vote up
public static boolean createDir(File folder) {
    if (folder.exists())
        return false;

    if (folder.mkdir())
        return true;
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DocumentFile document = DocumentFile.fromFile(folder.getParentFile());
            if (document.exists())
                return true;
        }

        if (Settings.rootAccess()) {
            return RootCommands.createRootdir(folder);
        }
    }

    return false;
}
 
Example 3
Source File: TGSafBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void listElements(TGBrowserCallBack<List<TGBrowserElement>> cb) {
	try {
		List<TGBrowserElement> elements = new ArrayList<TGBrowserElement>();
		if( this.element != null ) {
			DocumentFile file = this.element.getFile();
			if( file.exists() && file.isDirectory() ) {
				DocumentFile[] children = file.listFiles();
				if( children != null ) {
					for(DocumentFile child : children){
						elements.add(new TGSafBrowserElement(child, this.element));
					}
				}
			}
			if( !elements.isEmpty() ){
				Collections.sort(elements, new TGBrowserElementComparator());
			}
		}

		cb.onSuccess(elements);
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example 4
Source File: SettingsImpl.java    From ToGoZip with GNU General Public License v3.0 6 votes vote down vote up
/**
 * return true if outputdirectory of zipfile is writable
 */
public static boolean canWrite(Context context, String dir) {
    if ((dir == null) || (dir.trim().length() == 0)) {
        return false; // empty is no valid path
    }

    if (Global.USE_DOCUMENT_PROVIDER) {
        DocumentFile docDir = getDocFile(context, dir);
        return ((docDir != null) && (docDir.exists()) && docDir.canWrite());
    }

    File fileDir = new File(dir);
    if ((fileDir == null) || (!fileDir.exists() && !fileDir.mkdirs())) {
        return false; // parentdir does not exist and cannot be created
    }

    return true; // (parentDir.canWrite());
}
 
Example 5
Source File: SimpleUtils.java    From SimpleExplorer with GNU General Public License v3.0 6 votes vote down vote up
public static boolean createDir(File folder) {
    if (folder.exists())
        return false;

    if (folder.mkdir())
        return true;
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DocumentFile document = DocumentFile.fromFile(folder.getParentFile());
            if (document.exists())
                return true;
        }

        if (Settings.rootAccess()) {
            return RootCommands.createRootdir(folder);
        }
    }

    return false;
}
 
Example 6
Source File: FileUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a folder. The folder may even be on external SD card for Kitkat.
 *
 * @deprecated use {@link #mkdirs(Context, HFile)}
 * @param file  The folder to be created.
 * @return True if creation was successful.
 */
public static boolean mkdir(final File file, Context context) {
    if(file==null)
        return false;
    if (file.exists()) {
        // nothing to create.
        return file.isDirectory();
    }

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

    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && FileUtil.isOnExtSdCard(file, context)) {
        DocumentFile document = getDocumentFile(file, true, context);
        // getDocumentFile implicitly creates the directory.
        return document.exists();
    }

    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        try {
            return MediaStoreHack.mkdir(context, file);
        } catch (IOException e) {
            return false;
        }
    }

    return false;
}
 
Example 7
Source File: OTGUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Traverse to a specified path in OTG
 *
 * @param path
 * @param context
 * @param createRecursive flag used to determine whether to create new file while traversing to path,
 *                        in case path is not present. Notably useful in opening an output stream.
 * @return
 */
public static DocumentFile getDocumentFile(String path, Context context, boolean createRecursive) {
    SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(context);
    String rootUriString = manager.getString(ExplorerActivity.KEY_PREF_OTG, null);

    // start with root of SD card and then parse through document tree.
    DocumentFile rootUri = DocumentFile.fromTreeUri(context, Uri.parse(rootUriString));

    String[] parts = path.split("/");
    for (int i = 0; i < parts.length; i++) {

        if (path.equals("otg:/")) break;
        if (parts[i].equals("otg:") || parts[i].equals("")) continue;
        Log.d(context.getClass().getSimpleName(), "Currently at: " + parts[i]);
        // iterating through the required path to find the end point

        DocumentFile nextDocument = rootUri.findFile(parts[i]);
        if (createRecursive) {
            if (nextDocument == null || !nextDocument.exists()) {
                nextDocument = rootUri.createFile(parts[i].substring(parts[i].lastIndexOf(".")), parts[i]);
                Log.d(context.getClass().getSimpleName(), "NOT FOUND! File created: " + parts[i]);
            }
        }
        rootUri = nextDocument;
    }
    return rootUri;
}
 
Example 8
Source File: OutputUtil.java    From apkextractor with GNU General Public License v3.0 5 votes vote down vote up
public static @Nullable DocumentFile getWritingDocumentFileForAppItem(@NonNull Context context,@NonNull AppItem appItem,@NonNull String extension,int sequence_number) throws Exception{
    String writingFileName=getWriteFileNameForAppItem(context,appItem,extension,sequence_number);
    DocumentFile parent=getExportPathDocumentFile(context);
    DocumentFile documentFile=parent.findFile(writingFileName);
    if(documentFile!=null&&documentFile.exists())documentFile.delete();
    return parent.createFile(extension.toLowerCase().equals("apk")?"application/vnd.android.package-archive":"application/x-zip-compressed",writingFileName);
}
 
Example 9
Source File: OTGUtil.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
/**
   * Returns an array of list of files at a specific path in OTG
   *
   * @param path    the path to the directory tree, starts with prefix 'otg:/'
   *                Independent of URI (or mount point) for the OTG
   * @param context context for loading
   * @return an array of list of files at the path
   */
  public static ArrayList<BaseFile> getDocumentFilesList(final String path, final Context context, final ContentFragment.LoadFiles updater) {
      final SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(context);
      final String rootUriString = manager.getString(ExplorerActivity.KEY_PREF_OTG, null);
      DocumentFile rootUri = DocumentFile.fromTreeUri(context, Uri.parse(rootUriString));
      ArrayList<BaseFile> files = new ArrayList<>(1024);

      final String[] parts = path.split("/");
      for (int i = 0; i < parts.length; i++) {

          // first omit 'otg:/' before iterating through DocumentFile
          if (path.equals(OTGUtil.PREFIX_OTG + "/")) break;
          if (parts[i].equals("otg:") || parts[i].equals("")) continue;
          Log.d(context.getClass().getSimpleName(), "Currently at: " + parts[i]);
          // iterating through the required path to find the end point
          rootUri = rootUri.findFile(parts[i]);
      }

long prevUpdate = System.currentTimeMillis();
Log.d(context.getClass().getSimpleName(), "Found URI for: " + rootUri.getName());
      // we have the end point DocumentFile, list the files inside it and return
      for (DocumentFile file : rootUri.listFiles()) {
          try {
              if (file.exists()) {
                  long size = 0;
                  if (!file.isDirectory()) size = file.length();
                  Log.d(context.getClass().getSimpleName(), "Found file: " + file.getName());
                  BaseFile baseFile = new BaseFile(path + "/" + file.getName(),
                          RootHelper.parseDocumentFilePermission(file), file.lastModified(), size, file.isDirectory());
                  baseFile.setName(file.getName());
                  baseFile.setMode(OpenMode.OTG);
                  files.add(baseFile);
			final long present = System.currentTimeMillis();
			if (updater != null && present - prevUpdate > 1000 && !updater.busyNoti) {
				prevUpdate = present;
				updater.publish(files);
				files = new ArrayList<>(1024);
			}
              }
          } catch (Exception e) {
          }
      }
if (updater != null) {
	updater.publish(files);
}
      return files;
  }
 
Example 10
Source File: AndroidPathUtils.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Create a folder. The folder may even be on external SD card for Kitkat.
 *
 * @param file The folder to be created.
 * @return True if creation was successful.
 */
public static boolean mkdir(@NonNull final File file, final Context c) {
	if (file.exists()) {
		// nothing to create.
		return file.isDirectory();
	}

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

	// Try with Storage Access Framework.
	if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)) {
		DocumentFile document = getDocumentFile(file, true, true, c);
		// getDocumentFile implicitly creates the directory.
		return document != null && document.exists();
	}

	// Try the Kitkat workaround.
	if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
		File tempFile = new File(file, "dummyImage.jpg");

		File dummySong = copyDummyFiles(c);
		if (dummySong == null) {
			return false;
		}
		int albumId = getAlbumIdFromAudioFile(dummySong, c);
		Uri albumArtUri = Uri.parse("content://media/external/audio/albumart/" + albumId);

		ContentValues contentValues = new ContentValues();
		contentValues.put(MediaStore.MediaColumns.DATA, tempFile.getAbsolutePath());
		contentValues.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId);

		ContentResolver resolver = c.getContentResolver();
		if (resolver.update(albumArtUri, contentValues, null, null) == 0) {
			resolver.insert(Uri.parse("content://media/external/audio/albumart"), contentValues);
		}
		try {
			ParcelFileDescriptor fd = resolver.openFileDescriptor(albumArtUri, "r");
			if (fd != null) {
				fd.close();
			}
		}
		catch (Exception e) {
			Log.e("Uri", "Could not open file", e);
			return false;
		}
		finally {
			AndroidPathUtils.deleteFile(tempFile, c);
		}

		return true;
	}

	return false;
}