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

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

Introduction

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

Prototype

public abstract boolean renameTo(String str);

Source Link

Usage

From source file:com.filemanager.free.filesystem.FileUtil.java

/**
 * Rename a folder. In case of extSdCard in Kitkat, the old folder stays in place, but files are moved.
 *
 * @param source The source folder.//  w  ww  .  ja v a 2 s .com
 * @param target The target folder.
 * @return true if the renaming was successful.
 */
public static final boolean renameFolder(@NonNull final File source, @NonNull final File target,
        Context context) {
    // First try the normal rename.
    if (new Futils().rename(source, target.getName(), false)) {
        return true;
    }
    if (target.exists()) {
        return false;
    }

    // Try the Storage Access Framework if it is just a rename within the same parent folder.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && source.getParent().equals(target.getParent())
            && FileUtil.isOnExtSdCard(source, context)) {
        DocumentFile document = getDocumentFile(source, true, context);
        if (document.renameTo(target.getName())) {
            return true;
        }
    }

    // Try the manual way, moving files individually.
    if (!mkdir(target, context)) {
        return false;
    }

    File[] sourceFiles = source.listFiles();

    if (sourceFiles == null) {
        return true;
    }

    for (File sourceFile : sourceFiles) {
        String fileName = sourceFile.getName();
        File targetFile = new File(target, fileName);
        if (!copyFile(sourceFile, targetFile, context)) {
            // stop on first error
            return false;
        }
    }
    // Only after successfully copying all files, delete files on source folder.
    for (File sourceFile : sourceFiles) {
        if (!deleteFile(sourceFile, context)) {
            // stop on first error
            return false;
        }
    }
    return true;
}

From source file:com.veniosg.dir.mvvm.model.storage.operation.RenameOperation.java

@Override
public boolean operateSaf(RenameArguments args) {
    File from = args.getFileToRename();
    File dest = args.getTarget();

    if (dest.exists()) {
        return true;
    } else {/*from   ww  w.  j  a v  a 2  s  .c o m*/
        DocumentFile safFrom = findFile(context, from);
        return safFrom != null && safFrom.renameTo(args.getTarget().getName());
    }
}

From source file:com.osama.cryptofm.tasks.RenameTask.java

@Override
protected String doInBackground(Void... voids) {
    try {//from   ww w . j a  v a2s . co  m
        if (FileUtils.isDocumentFile(mFilePath)) {
            Log.d("niggers", "doInBackground: renaming document file");
            DocumentFile file = FileDocumentUtils.getDocumentFile(new File(mFilePath));
            assert file != null;
            if (file.renameTo(mRenamed)) {

                return "successfully renamed";
            } else {
                return "Cannot rename file";
            }
        }
        Log.d("niggers", "doInBackground: current path is: " + FileUtils.CURRENT_PATH);
        File file = TasksFileUtils.getFile(mFilePath);
        String filename = file.getPath();
        filename = filename.replace(file.getName(), "");
        File renamedFile = new File(filename + mRenamed);
        if (file.renameTo(renamedFile)) {
            return "successfully renamed.";
        }
    } catch (Exception ex) {
        ex.getMessage();
        return "cannot rename file.";
    }
    return "cannot rename file.";
}

From source file:de.k3b.android.toGoZip.ZipStorageDocumentFile.java

/**
 *  {@inheritDoc}/* ww w . j a  v  a 2  s  .c o  m*/
 */
@Override
public boolean rename(ZipInstance zipInstanceFrom, ZipInstance zipInstanceTo) {
    DocumentFile zipFile = directory.findFile(getZipFileNameWithoutPath(zipInstanceFrom));
    if (zipFile != null)
        return zipFile.renameTo(getZipFileNameWithoutPath(zipInstanceTo));
    return false;
}

From source file:com.xperia64.timidityae.Globals.java

public static boolean renameDocumentFile(Context c, String from, String subTo) {
    // From is the full path
    // subTo is the path without the device prefix. 
    // So /storage/sdcard1/folder/file.mid should be folder/file.mid
    if (theFold == null)
        return false;
    from = from.replace("//", "/");
    subTo = subTo.replace("//", "/");
    DocumentFile df = DocumentFile.fromTreeUri(c, theFold);
    String split[] = from.split("/");
    int i;/*w  ww.ja  va 2s  .c om*/
    for (i = 0; i < split.length; i++) {
        if (split[i].equals(df.getName())) {
            i++;
            break;
        }
    }
    DocumentFile xx = df;
    StringBuilder upper = new StringBuilder();
    while (i < split.length) {
        xx = xx.findFile(split[i++]);
        upper.append("../");
        if (xx == null) {
            Log.e("TimidityAE Globals", "Rename file error.");
            break;
        }
    }
    if (xx != null && upper.length() > 3) {
        return xx.renameTo(upper.substring(0, upper.length() - 3) + subTo);
    }
    return false;
}

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

protected void doExportVideo() {
    boolean onPause = this.onPause;
    this.onPause = false;
    boolean isDro = this.modeDRO();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && (documentFileSaved != null || !isDro)) {
        DocumentFile fileSaved = VideoCapturePlugin.documentFileSaved;
        ArrayList<DocumentFile> filesListToExport = documentFilesList;
        String resultName = fileSaved.getName();
        DocumentFile resultFile = fileSaved;

        if (filesListToExport.size() > 0) {
            int inputFileCount = filesListToExport.size();
            if (!onPause)
                inputFileCount++;//from  www  .  ja v a 2s .c o m

            DocumentFile[] inputFiles = new DocumentFile[inputFileCount];

            for (int i = 0; i < filesListToExport.size(); i++) {
                inputFiles[i] = filesListToExport.get(i);
            }

            // If video recording hadn't been paused before STOP was
            // pressed, then last recorded file is not in the list with
            // other files, added to list of files manually.
            if (!onPause) {
                inputFiles[inputFileCount - 1] = fileSaved;
            }

            resultFile = appendNew(inputFiles);

            // Remove merged files, except first one, because it stores the
            // result of merge.
            for (int i = 0; i < filesListToExport.size(); i++) {
                DocumentFile currentFile = filesListToExport.get(i);
                currentFile.delete();
            }

            // If video recording hadn't been paused before STOP was
            // pressed, then last recorded file is not in the list with
            // other files, and should be deleted manually.
            if (!onPause)
                fileSaved.delete();

            String tmpName = resultFile.getName();
            if (resultFile.renameTo(resultName))
                ;

            // Make sure, that there won't be duplicate broken file
            // in phone memory at gallery.
            String args[] = { tmpName };
            ApplicationScreen.instance.getContentResolver().delete(Video.Media.EXTERNAL_CONTENT_URI,
                    Video.Media.DISPLAY_NAME + "=?", args);
        }

        String name = resultFile.getName();
        String data = null;
        // If we able to get File object, than get path from it. Gallery
        // doesn't show the file, if it's stored at phone memory and
        // we need insert new file to gallery manually.
        File file = Util.getFileFromDocumentFile(resultFile);
        if (file != null) {
            data = file.getAbsolutePath();
        } else {
            // This case should typically happen for files saved to SD
            // card.
            data = Util.getAbsolutePathFromDocumentFile(resultFile);
        }

        if (data != null) {
            values.put(VideoColumns.DISPLAY_NAME, name);
            values.put(VideoColumns.DATA, data);
            Uri uri = ApplicationScreen.instance.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
                    values);
            ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
        }
    } else {
        File fileSaved = VideoCapturePlugin.fileSaved;
        ArrayList<File> filesListToExport = filesList;

        File firstFile = fileSaved;

        if (filesListToExport.size() > 0) {
            firstFile = filesListToExport.get(0);

            int inputFileCount = filesListToExport.size();
            if (!onPause)
                inputFileCount++;

            File[] inputFiles = new File[inputFileCount];

            for (int i = 0; i < filesListToExport.size(); i++) {
                inputFiles[i] = filesListToExport.get(i);
            }

            if (!onPause)
                inputFiles[inputFileCount - 1] = fileSaved;

            File resultFile = append(inputFiles);

            for (int i = 0; i < filesListToExport.size(); i++) {
                File currentFile = filesListToExport.get(i);
                currentFile.delete();
            }

            if (resultFile != null) {
                if (!resultFile.getAbsoluteFile().equals(fileSaved.getAbsoluteFile())) {
                    fileSaved.delete();
                    resultFile.renameTo(fileSaved);
                }
            }
        }

        filesListToExport.clear();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && isDro) {
            DocumentFile outputFile = getOutputMediaDocumentFile();
            File file = Util.getFileFromDocumentFile(outputFile);

            if (file != null) {
                // Don't do anything with ouputFile. It's useless, remove
                // it.
                outputFile.delete();
                Uri uri = ApplicationScreen.instance.getContentResolver()
                        .insert(Video.Media.EXTERNAL_CONTENT_URI, values);
                ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
            } else {
                // Copy result file from phone memory to selected folder at
                // SD-card.
                InputStream is = null;
                int len;
                byte[] buf = new byte[4096];
                try {
                    OutputStream os = ApplicationScreen.instance.getContentResolver()
                            .openOutputStream(outputFile.getUri());
                    is = new FileInputStream(firstFile);
                    while ((len = is.read(buf)) > 0) {
                        os.write(buf, 0, len);
                    }
                    is.close();
                    os.close();
                    firstFile.delete();

                    // Make sure, that there won't be duplicate broken file
                    // in phone memory at gallery.
                    String args[] = { firstFile.getAbsolutePath() };
                    ApplicationScreen.instance.getContentResolver().delete(Video.Media.EXTERNAL_CONTENT_URI,
                            Video.Media.DATA + "=?", args);

                    String data = Util.getAbsolutePathFromDocumentFile(outputFile);
                    if (data != null) {
                        values.put(VideoColumns.DATA, data);
                        Uri uri = ApplicationScreen.instance.getContentResolver()
                                .insert(Video.Media.EXTERNAL_CONTENT_URI, values);
                        ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            Uri uri = ApplicationScreen.instance.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
                    values);
            ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
        }
    }

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);

}