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

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

Introduction

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

Prototype

public abstract String getName();

Source Link

Usage

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

public static void tryToDeleteFile(Context c, String filename) {
    filename = filename.replace("//", "/");
    if (new File(filename).exists()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) {
            DocumentFile df = DocumentFile.fromTreeUri(c, theFold);
            String split[] = filename.split("/");
            int i;
            for (i = 0; i < split.length; i++) {
                if (split[i].equals(df.getName())) {
                    i++;/*w  ww.j  a v a  2  s  .  c  om*/
                    break;
                }
            }
            DocumentFile xx = df;
            while (i < split.length) {
                xx = xx.findFile(split[i++]);
                //upper.append("../");
                if (xx == null) {
                    Log.e("TimidityAE Globals", "Delete file error.");
                    break;
                }
            }
            // Why on earth is DocumentFile's delete method recursive by default?
            // Seriously. I wiped my sd card twice because of this.
            if (xx != null && xx.isFile() && !xx.isDirectory()) {
                xx.delete();
            }
        } else {
            new File(filename).delete();
        }
    }
}

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

public static void tryToCreateFile(Context c, String filename) {
    filename = filename.replace("//", "/");
    if (!(new File(filename).exists())) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && theFold != null) {
            DocumentFile df = DocumentFile.fromTreeUri(c, theFold);
            String split[] = filename.split("/");
            int i;
            for (i = 0; i < split.length; i++) {
                if (split[i].equals(df.getName())) {
                    i++;//from w  w w  .  j  ava2s .co m
                    break;
                }
            }
            DocumentFile xx = df;
            while (i < split.length - 1) {
                xx = xx.findFile(split[i++]);
                if (xx == null) {
                    Log.e("TimidityAE Globals", "Create file error.");
                    break;
                }
            }
            if (xx != null) {
                xx.createFile("timidityae/tpl", split[split.length - 1]);
            }
        } else {
            try {
                new File(filename).createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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

private ArrayList<String> getOnlyEncryptedDocumentFiles(ArrayList<String> files) {
    int size = files.size();
    for (int i = 0; i < size; i++) {
        DocumentFile file = FileDocumentUtils.getDocumentFile(new File(files.get(i)));
        //check if file is directory
        assert file != null;
        if (file.isDirectory()) {
            //get all the lists of files in directory
            ArrayList<String> tmp = new ArrayList<>();
            for (DocumentFile f : file.listFiles()) {
                tmp.add(FileUtils.CURRENT_PATH + f.getName());
            }/*from w w  w . ja va 2s. co m*/
            //recursively get files
            getOnlyEncryptedDocumentFiles(tmp);
        }
        if (FileUtils.isEncryptedFile(mFilePaths.get(i))) {
            tmp.add(mFilePaths.get(i));
        }
    }
    //if there are no encrypted file
    if (tmp.size() < 1) {
        throw new IllegalArgumentException("No encrypted files found.");
    }
    return tmp;
}

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

private void moveDocumentFile(DocumentFile file) throws Exception {
    if (file.isDirectory()) {
        Log.d(TAG, "moveDocumentFile: Yes document file is directory");
        //change the destination folder
        mDestinationFolder = mDestinationFolder + file.getName() + "/";
        //check if destination folder is not document file
        if (FileUtils.isDocumentFile(mDestinationFolder)) {
            rootDocumentFile = rootDocumentFile.createDirectory(file.getName());
        } else {/*from w w  w  .j ava2s  .c o  m*/
            File tmp = new File(mDestinationFolder);
            if (!tmp.exists()) {
                tmp.mkdir();
            } else {
                return;
            }
        }
        for (DocumentFile f : file.listFiles()) {
            moveDocumentFile(f);
        }
    } else {
        isNextFile = true;
        publishProgress(file.getName());
        publishProgress("" + 0);
        //check if pasting in internal storage
        if (!FileUtils.isDocumentFile(mDestinationFolder)) {
            Log.d(TAG, "moveDocumentFile: moving document file in internal storage");
            File destinationFile = new File(mDestinationFolder + file.getName());
            innerMove(CryptoFM.getContext().getContentResolver().openInputStream(file.getUri()),
                    new BufferedOutputStream(new FileOutputStream(destinationFile)), file.length());
        } else {
            Log.d(TAG, "moveDocumentFile: Moving document file honey");
            DocumentFile destFile = rootDocumentFile.createFile(file.getType(), file.getName());

            innerMove(CryptoFM.getContext().getContentResolver().openInputStream(file.getUri()),
                    CryptoFM.getContext().getContentResolver().openOutputStream(destFile.getUri()),
                    file.length());
        }
    }

    //delete the input file
    //if copying then don't
    if (SharedData.IS_COPYING_NOT_MOVING) {
        return;
    }
    if (!file.delete()) {
        throw new IOException("cannot move files");
    }
}

From source file:freed.ActivityAbstract.java

@Nullable
private boolean deletFile(File file) {
    if (!file.delete()) {
        DocumentFile sdDir = getExternalSdDocumentFile();
        if (sdDir == null)
            return false;
        String baseS = sdDir.getName();
        String fileFolder = file.getAbsolutePath();
        String[] split = fileFolder.split("/");
        DocumentFile tmpdir = null;//  w ww . jav  a2  s  .c  om
        boolean append = false;
        for (String aSplit : split) {
            if (aSplit.equals(baseS) || append) {
                if (!append) {
                    append = true;
                    tmpdir = sdDir;
                } else {
                    tmpdir = tmpdir.findFile(aSplit);
                }
            }
        }
        boolean d = false;
        d = !(tmpdir != null && tmpdir.exists()) || tmpdir.delete();
        Log.d("delteDocumentFile", "file delted:" + d);
        return d;
    }
    return true;
}

From source file:com.kanedias.vanilla.audiotag.PluginService.java

/**
 * Finds needed file through Document API for SAF. It's not optimized yet - you can still gain wrong URI on
 * files such as "/a/b/c.mp3" and "/b/a/c.mp3", but I consider it complete enough to be usable.
 * @param currentDir - document file representing current dir of search
 * @param remainingPathSegments - path segments that are left to find
 * @return URI for found file. Null if nothing found.
 *//*w ww.  j a  v a 2  s.c  o  m*/
@Nullable
private Uri findInDocumentTree(DocumentFile currentDir, List<String> remainingPathSegments) {
    for (DocumentFile file : currentDir.listFiles()) {
        int index = remainingPathSegments.indexOf(file.getName());
        if (index == -1) {
            continue;
        }

        if (file.isDirectory()) {
            remainingPathSegments.remove(file.getName());
            return findInDocumentTree(file, remainingPathSegments);
        }

        if (file.isFile() && index == remainingPathSegments.size() - 1) {
            // got to the last part
            return file.getUri();
        }
    }

    return null;
}

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

@Override
protected String doInBackground(Void... voids) {
    try {//from  w  w w. j  a  v  a  2 s. c o 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:com.commonsware.android.tte.DocumentStorageService.java

private void load(Uri document) {
    try {/*from w  w w .  j  a  v  a  2s.c om*/
        boolean weHavePermission = false;
        boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme());

        if (isContent) {
            int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

            getContentResolver().takePersistableUriPermission(document, perms);

            for (UriPermission perm : getContentResolver().getPersistedUriPermissions()) {
                if (perm.getUri().equals(document)) {
                    weHavePermission = true;
                }
            }
        } else {
            weHavePermission = true;
        }

        if (weHavePermission) {
            try {
                InputStream is = getContentResolver().openInputStream(document);

                try {
                    String text = slurp(is);
                    DocumentFile docFile;

                    if (isContent) {
                        docFile = DocumentFile.fromSingleUri(this, document);
                    } else {
                        docFile = DocumentFile.fromFile(new File(document.getPath()));
                    }

                    EventBus.getDefault().post(
                            new DocumentLoadedEvent(document, text, docFile.getName(), docFile.canWrite()));
                } finally {
                    is.close();
                }
            } catch (Exception e) {
                Log.e(getClass().getSimpleName(), "Exception loading " + document.toString(), e);
                EventBus.getDefault().post(new DocumentLoadErrorEvent(document, e));
            }
        } else {
            Log.e(getClass().getSimpleName(), "We failed to get permissions for " + document.toString());
            EventBus.getDefault().post(new DocumentPermissionFailureEvent(document));
        }
    } catch (SecurityException e) {
        Log.e(getClass().getSimpleName(), "Exception getting permissions for " + document.toString(), e);
        EventBus.getDefault().post(new DocumentPermissionFailureEvent(document));
    }
}

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

private void decryptDocumentFiles(DocumentFile f) throws Exception {
    Log.d(TAG, "decryptDocumentFiles: Running decryption on document file");
    //first always check if task is canceled
    if (!isCancelled()) {
        if (f.isDirectory()) {
            for (DocumentFile tmpFile : f.listFiles()) {
                decryptDocumentFiles(tmpFile);
            }//w  w w . j av  a 2  s.  c om
        } else {
            File out = new File(rootPath + "/", f.getName().substring(0, f.getName().lastIndexOf('.')));
            // add the file in created files. top remove the files later of user cancels the task
            mCreatedFiles.add(out.getAbsoluteFile());
            publishProgress(f.getName(), "" + ((FileUtils.getReadableSize((f.length())))));

            DocumentFileEncryption.decryptFile(
                    CryptoFM.getContext().getContentResolver().openInputStream(f.getUri()), getSecretKey(),
                    mKeyPass, new BufferedOutputStream(new FileOutputStream(out))

            );

        }
    }
}

From source file:com.maskyn.fileeditorpro.dialogfragment.FileInfoDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    View view = new DialogHelper.Builder(getActivity()).setTitle(R.string.info)
            .setView(R.layout.dialog_fragment_file_info).createSkeletonView();
    //final View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_fragment_file_info, null);

    ListView list = (ListView) view.findViewById(android.R.id.list);

    DocumentFile file = DocumentFile.fromFile(
            new File(AccessStorageApi.getPath(getActivity(), (Uri) getArguments().getParcelable("uri"))));

    if (file == null && Device.hasKitKatApi()) {
        file = DocumentFile.fromSingleUri(getActivity(), (Uri) getArguments().getParcelable("uri"));
    }/*  www.j a v  a  2 s .  c o  m*/

    // Get the last modification information.
    Long lastModified = file.lastModified();

    // Create a new date object and pass last modified information
    // to the date object.
    Date date = new Date(lastModified);

    String[] lines1 = { getString(R.string.name),
            //getString(R.string.folder),
            getString(R.string.size), getString(R.string.modification_date) };
    String[] lines2 = { file.getName(),
            //file.getParent(),
            FileUtils.byteCountToDisplaySize(file.length()), date.toString() };

    list.setAdapter(new AdapterTwoItem(getActivity(), lines1, lines2));

    return new AlertDialog.Builder(getActivity()).setView(view)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).create();
}