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

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

Introduction

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

Prototype

public DocumentFile findFile(String str) 

Source Link

Usage

From source file:io.v.syncslides.lib.DeckImporter.java

private byte[] readImage(DocumentFile dir, String fileName) throws IOException {
    DocumentFile file = dir.findFile(fileName);
    if (file == null) {
        throw new FileNotFoundException("Image file doesn't exist: " + fileName);
    }/*w w  w  .j  a v a 2s  .c o  m*/
    return ByteStreams.toByteArray(mContentResolver.openInputStream(file.getUri()));
}

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;//ww w  .  j ava 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.filemanager.free.filesystem.FileUtil.java

/**
 * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If the file is not
 * existing, it is created./*www .  j  a  va2  s . c o m*/
 *
 * @param file        The file.
 * @param isDirectory flag indicating if the file should be a directory.
 * @return The DocumentFile
 */
public static DocumentFile getDocumentFile(final File file, final boolean isDirectory, Context context) {
    String baseFolder = getExtSdCardFolder(file, context);
    boolean originalDirectory = false;
    if (baseFolder == null) {
        return null;
    }

    String relativePath = null;
    try {
        String fullPath = file.getCanonicalPath();
        if (!baseFolder.equals(fullPath))
            relativePath = fullPath.substring(baseFolder.length() + 1);
        else
            originalDirectory = true;
    } catch (IOException e) {
        return null;
    } catch (Exception f) {
        originalDirectory = true;
        //continue
    }
    String as = PreferenceManager.getDefaultSharedPreferences(context).getString("URI", null);

    Uri treeUri = null;
    if (as != null)
        treeUri = Uri.parse(as);
    if (treeUri == null) {
        return null;
    }

    // start with root of SD card and then parse through document tree.
    DocumentFile document = DocumentFile.fromTreeUri(context, treeUri);
    if (originalDirectory)
        return document;
    String[] parts = relativePath.split("\\/");
    for (int i = 0; i < parts.length; i++) {
        DocumentFile nextDocument = document.findFile(parts[i]);

        if (nextDocument == null) {
            if ((i < parts.length - 1) || isDirectory) {
                nextDocument = document.createDirectory(parts[i]);
            } else {
                nextDocument = document.createFile("image", parts[i]);
            }
        }
        document = nextDocument;
    }

    return document;
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static DocumentFile getDirectory(Context context, File dir, boolean create) {
    try {//  w w  w.  j  av  a2 s .c  o  m
        String path = dir.getAbsolutePath();
        DocumentFile cached = CACHE.get(path);
        if (cached != null && cached.isDirectory()) {
            return cached;
        }

        String baseFolder = getExtSdCardFolder(context, dir);
        if (baseFolder == null) {
            if (create) {
                return dir.mkdirs() ? DocumentFile.fromFile(dir) : null;
            } else {
                return dir.isDirectory() ? DocumentFile.fromFile(dir) : null;
            }
        }

        baseFolder = combineRoot(baseFolder);

        String fullPath = dir.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);

        // special FrostWire case
        if (create) {
            if (baseFolder.endsWith("/FrostWire") && !f.exists()) {
                baseFolder = baseFolder.substring(0, baseFolder.length() - 10);
                rootUri = getDocumentUri(context, new File(baseFolder));
                f = DocumentFile.fromTreeUri(context, rootUri);
                f = f.findFile("FrostWire");
                if (f == null) {
                    f = f.createDirectory("FrostWire");
                    if (f == null) {
                        return null;
                    }
                }
            }
        }
        for (String segment : segments) {
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                if (create) {
                    f = f.createDirectory(segment);
                    if (f == null) {
                        return null;
                    }
                } else {
                    return null;
                }
            }
        }

        f = f.isDirectory() ? f : null;

        if (f != null) {
            CACHE.put(path, f);
        }

        return f;
    } catch (Throwable e) {
        LOG.error("Error getting directory: " + dir, e);
        return null;
    }
}

From source file:io.v.android.apps.syncslides.DeckChooserFragment.java

private byte[] readImage(DocumentFile dir, String fileName) throws IOException {
    DocumentFile file = dir.findFile(fileName);
    if (file == null) {
        throw new FileNotFoundException("Image file doesn't exist: " + fileName);
    }//from   w ww  . java2s  .co  m
    return ByteStreams.toByteArray(getActivity().getContentResolver().openInputStream(file.getUri()));
}

From source file:io.v.syncslides.lib.DeckImporter.java

private Void importDeckImpl(DocumentFile dir) throws ImportException {
    if (!dir.isDirectory()) {
        throw new ImportException("Must import from a directory, got: " + dir);
    }// w w  w. ja va 2  s  .  c  o  m
    // Read the deck metadata file.
    DocumentFile metadataFile = dir.findFile(DECK_JSON);
    if (metadataFile == null) {
        throw new ImportException("Couldn't find deck metadata file 'deck.json'");
    }
    JSONObject metadata = null;
    try {
        String data = new String(
                ByteStreams.toByteArray(mContentResolver.openInputStream(metadataFile.getUri())),
                Charsets.UTF_8);
        metadata = new JSONObject(data);
    } catch (FileNotFoundException e) {
        throw new ImportException("Couldn't open deck metadata file", e);
    } catch (IOException e) {
        throw new ImportException("Couldn't read data from deck metadata file", e);
    } catch (JSONException e) {
        throw new ImportException("Couldn't parse deck metadata", e);
    }

    try {
        String id = UUID.randomUUID().toString();
        String title = metadata.getString(TITLE);
        byte[] thumbData = readImage(dir, metadata.getString(THUMB));
        Deck deck = new DeckImpl(title, thumbData, id);
        Slide[] slides = readSlides(dir, metadata);
        sync(mDB.importDeck(deck, slides));
    } catch (JSONException e) {
        throw new ImportException("Invalid format for deck metadata", e);
    } catch (IOException e) {
        throw new ImportException("Error interpreting deck metadata", e);
    } catch (VException e) {
        throw new ImportException("Error importing deck", e);
    }
    return null;
}

From source file:io.v.android.apps.syncslides.DeckChooserFragment.java

/**
 * Import a slide deck from the given (local) folder.
 *
 * The folder must contain a JSON metadata file 'deck.json' with the following format:
 * {//from w  w  w  .  ja  v  a  2s . c o  m
 *     "Title" : "<title>",
 *     "Thumb" : "<filename>,
 *     "Slides" : [
 *          {
 *              "Thumb" : "<thumb_filename1>",
 *              "Image" : "<image_filename1>",
 *              "Note" : "<note1>"
 *          },
 *          {
 *              "Thumb" : "<thumb_filename2>",
 *              "Image" : "<image_filename2>",
 *              "Note" : "<note2>"
 *          },
 *
 *          ...
 *     ]
 * }
 *
 * All the filenames must be local to the given folder.
 */
private void importDeck(DocumentFile dir) {
    if (!dir.isDirectory()) {
        toast("Must import from a directory, got: " + dir);
        return;
    }
    // Read the deck metadata file.
    DocumentFile metadataFile = dir.findFile("deck.json");
    if (metadataFile == null) {
        toast("Couldn't find deck metadata file 'deck.json'");
        return;
    }
    JSONObject metadata = null;
    try {
        String data = new String(
                ByteStreams
                        .toByteArray(getActivity().getContentResolver().openInputStream(metadataFile.getUri())),
                Charsets.UTF_8);
        metadata = new JSONObject(data);
    } catch (FileNotFoundException e) {
        toast("Couldn't open deck metadata file: " + e.getMessage());
        return;
    } catch (IOException e) {
        toast("Couldn't read data from deck metadata file: " + e.getMessage());
        return;
    } catch (JSONException e) {
        toast("Couldn't parse deck metadata: " + e.getMessage());
        return;
    }

    try {
        String id = UUID.randomUUID().toString();
        String title = metadata.getString("Title");
        byte[] thumbData = readImage(dir, metadata.getString("Thumb"));
        Deck deck = DeckFactory.Singleton.get().make(title, thumbData, id);
        Slide[] slides = readSlides(dir, metadata);
        DB.Singleton.get(getActivity().getApplicationContext()).importDeck(deck, slides, null);
    } catch (JSONException e) {
        toast("Invalid format for deck metadata: " + e.getMessage());
        return;
    } catch (IOException e) {
        toast("Error interpreting deck metadata: " + e.getMessage());
        return;
    }
}

From source file:freed.ActivityAbstract.java

private DocumentFile getDCIMDocumentFolder(boolean create) {
    DocumentFile documentFile = null;//from   w ww.j a  va  2  s.  co  m
    DocumentFile sdDir;
    if ((sdDir = getExternalSdDocumentFile()) != null) {
        documentFile = sdDir.findFile("DCIM");
        if (documentFile == null && create)
            documentFile = sdDir.createDirectory("DCIM");
    }
    return documentFile;
}

From source file:freed.ActivityAbstract.java

@Override
public DocumentFile getFreeDcamDocumentFolder() {
    DocumentFile dcimfolder;
    DocumentFile freedcamfolder = null;//from   w w w .j  a v a 2 s .co m
    if ((dcimfolder = getDCIMDocumentFolder(true)) != null) {
        freedcamfolder = dcimfolder.findFile("FreeDcam");
        if (freedcamfolder == null)
            freedcamfolder = dcimfolder.createDirectory("FreeDcam");
    }
    return freedcamfolder;
}

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;
        boolean append = false;
        for (String aSplit : split) {
            if (aSplit.equals(baseS) || append) {
                if (!append) {
                    append = true;//from w w  w  .  ja v a2s .c om
                    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;
}