Example usage for android.support.v4.provider DocumentFile createDirectory

List of usage examples for android.support.v4.provider DocumentFile createDirectory

Introduction

In this page you can find the example usage for android.support.v4.provider DocumentFile createDirectory.

Prototype

public abstract DocumentFile createDirectory(String str);

Source Link

Usage

From source file:de.arcus.playmusiclib.PlayMusicManager.java

/**
 * Exports a track to the sd card/*from w w  w .  ja  v  a2s  . c  om*/
 * @param musicTrack The music track you want to export
 * @param uri The document tree
 * @return Returns whether the export was successful
 */
public boolean exportMusicTrack(MusicTrack musicTrack, Uri uri, String path) {

    // Check for null
    if (musicTrack == null)
        return false;

    String srcFile = musicTrack.getSourceFile();

    // Could not find the source file
    if (srcFile == null)
        return false;

    String fileTmp = getTempPath() + "/tmp.mp3";

    // Copy to temp path failed
    if (!SuperUserTools.fileCopy(srcFile, fileTmp))
        return false;

    // Encrypt the file
    if (musicTrack.isEncoded()) {
        String fileTmpCrypt = getTempPath() + "/crypt.mp3";

        // Encrypts the file
        if (trackEncrypt(musicTrack, fileTmp, fileTmpCrypt)) {
            // Remove the old tmp file
            FileTools.fileDelete(fileTmp);

            // New tmp file
            fileTmp = fileTmpCrypt;
        } else {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "Encrypting failed! Continue with decrypted file.");
        }
    }

    String dest;
    Uri copyUri = null;
    if (uri.toString().startsWith("file://")) {
        // Build the full path
        dest = uri.buildUpon().appendPath(path).build().getPath();

        String parentDirectory = new File(dest).getParent();
        FileTools.directoryCreate(parentDirectory);
    } else {
        // Complex uri (Lollipop)
        dest = getTempPath() + "/final.mp3";

        // The root
        DocumentFile document = DocumentFile.fromTreeUri(mContext, uri);

        // Creates the subdirectories
        String[] directories = path.split("\\/");
        for (int i = 0; i < directories.length - 1; i++) {
            String directoryName = directories[i];
            boolean found = false;

            // Search all sub elements
            for (DocumentFile subDocument : document.listFiles()) {
                // Directory exists
                if (subDocument.isDirectory() && subDocument.getName().equals(directoryName)) {
                    document = subDocument;
                    found = true;
                    break;
                }
            }

            if (!found) {
                // Create the directory
                document = document.createDirectory(directoryName);
            }
        }

        // Gets the filename
        String filename = directories[directories.length - 1];

        for (DocumentFile subDocument : document.listFiles()) {
            // Directory exists
            if (subDocument.isFile() && subDocument.getName().equals(filename)) {
                // Delete the file
                subDocument.delete();
                break;
            }
        }

        // Create the mp3 file
        document = document.createFile("music/mp3", filename);

        // Create the directories
        copyUri = document.getUri();
    }

    // We want to export the ID3 tags
    if (mID3Enable) {
        // Adds the meta data
        if (!trackWriteID3(musicTrack, fileTmp, dest)) {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "ID3 writer failed! Continue without ID3 tags.");

            // Failed, moving without meta data
            if (!FileTools.fileMove(fileTmp, dest)) {
                Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

                // Could not copy the file
                return false;
            }
        }
    } else {
        // Moving the file
        if (!FileTools.fileMove(fileTmp, dest)) {
            Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

            // Could not copy the file
            return false;
        }
    }

    // We need to copy the file to a uri
    if (copyUri != null) {
        // Lollipop only
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                // Gets the file descriptor
                ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver()
                        .openFileDescriptor(copyUri, "w");

                // Gets the output stream
                FileOutputStream fileOutputStream = new FileOutputStream(
                        parcelFileDescriptor.getFileDescriptor());

                // Gets the input stream
                FileInputStream fileInputStream = new FileInputStream(dest);

                // Copy the stream
                FileTools.fileCopy(fileInputStream, fileOutputStream);

                // Close all streams
                fileOutputStream.close();
                fileInputStream.close();
                parcelFileDescriptor.close();

            } catch (FileNotFoundException e) {
                Logger.getInstance().logError("ExportMusicTrack", "File not found!");

                // Could not copy the file
                return false;
            } catch (IOException e) {
                Logger.getInstance().logError("ExportMusicTrack",
                        "Failed to write the document: " + e.toString());

                // Could not copy the file
                return false;
            }
        }
    }

    // Delete temp files
    cleanUp();

    // Adds the file to the media system
    //new MediaScanner(mContext, dest);

    // Done
    return true;
}

From source file:com.almalence.opencam.SavingService.java

@TargetApi(19)
public static DocumentFile getSaveDirNew(boolean forceSaveToInternalMemory) {
    DocumentFile saveDir = null;
    boolean usePhoneMem = true;

    String abcDir = "Camera";
    if (sortByData) {
        Calendar rightNow = Calendar.getInstance();
        abcDir = String.format("%tF", rightNow);
    }//  ww w.  jav a 2s .  co  m

    int saveToValue = Integer.parseInt(saveToPreference);
    if (saveToValue == 1 || saveToValue == 2) {
        boolean canWrite = false;
        String uri = saveToPath;
        try {
            saveDir = DocumentFile.fromTreeUri(ApplicationScreen.instance, Uri.parse(uri));
        } catch (Exception e) {
            saveDir = null;
        }
        List<UriPermission> perms = ApplicationScreen.instance.getContentResolver()
                .getPersistedUriPermissions();
        for (UriPermission p : perms) {
            if (p.getUri().toString().equals(uri.toString()) && p.isWritePermission()) {
                canWrite = true;
                break;
            }
        }

        if (saveDir != null && canWrite && saveDir.exists()) {
            if (sortByData) {
                DocumentFile dateFolder = saveDir.findFile(abcDir);
                if (dateFolder == null) {
                    dateFolder = saveDir.createDirectory(abcDir);
                }
                saveDir = dateFolder;
            }
            usePhoneMem = false;
        }
    }

    if (usePhoneMem || forceSaveToInternalMemory) // phone memory (internal
    // sd card)
    {
        saveDir = DocumentFile
                .fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
        DocumentFile abcFolder = saveDir.findFile(abcDir);
        if (abcFolder == null || !abcFolder.exists()) {
            abcFolder = saveDir.createDirectory(abcDir);
        }
        saveDir = abcFolder;
    }

    return saveDir;
}