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

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

Introduction

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

Prototype

public abstract boolean exists();

Source Link

Usage

From source file:Main.java

@NonNull
public static boolean dirExistsAndIsWritable(DocumentFile appdir) {
    return appdir.exists() && appdir.canWrite();
}

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

private static DocumentFile getDirectory(Context context, File dir, boolean create) {
    try {/*from   w  w w. ja  v  a2  s  . c  om*/
        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:com.filemanager.free.filesystem.FileUtil.java

/**
 * 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.
 */// w ww. j  a va 2  s .com
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;
}

From source file:com.callrecorder.android.RecordingsAdapter.java

private void deleteRecord(final String fileName, final int position) {
    new AlertDialog.Builder(context).setTitle(R.string.confirm_delete_title)
            .setMessage(R.string.confirm_delete_text)
            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    DocumentFile file = FileHelper.getStorageFile(context).findFile(fileName);

                    if (file.exists() && file.delete()) {
                        list.remove(position);
                        notifyDataSetChanged();
                    } else {
                        Toast toast = Toast.makeText(getContext(),
                                getContext().getString(R.string.delete_failed), Toast.LENGTH_SHORT);
                        toast.show();//from  ww w. ja v  a 2 s  .  co m
                    }
                }
            }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            }).show();
}

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

@Override
public boolean exists(File file) {
    if (file.exists()) {
        return true;
    }// w  w  w  .ja va  2  s .c o m

    DocumentFile f = getDocument(app, file);

    return f != null && f.exists();
}

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   ww w.  j  av  a  2 s  .com
                    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.almalence.plugins.capture.video.VideoCapturePlugin.java

@TargetApi(19)
private static DocumentFile getOutputMediaDocumentFile() {
    DocumentFile saveDir = PluginManager.getSaveDirNew(false);

    if (saveDir == null || !saveDir.exists() || !saveDir.canWrite()) {
        saveDir = PluginManager.getSaveDirNew(true);
    }/*from  ww  w. j av a 2s  .c o m*/

    Calendar d = Calendar.getInstance();
    String fileFormat = String.format("%04d%02d%02d_%02d%02d%02d", d.get(Calendar.YEAR),
            d.get(Calendar.MONTH) + 1, d.get(Calendar.DAY_OF_MONTH), d.get(Calendar.HOUR_OF_DAY),
            d.get(Calendar.MINUTE), d.get(Calendar.SECOND));

    documentFileSaved = saveDir.createFile("video/mp4", fileFormat);
    return documentFileSaved;
}

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);
    }//from   w w w  .  j  a v  a  2  s  .  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;
}

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

private void saveInputFileNew(boolean isYUV, Long SessionID, int i, byte[] buffer, int yuvBuffer,
        String fileFormat) {/* w w  w.j a v a 2s  .  c  o  m*/

    int mImageWidth = Integer.parseInt(PluginManager.getInstance().getFromSharedMem("imageWidth" + SessionID));
    int mImageHeight = Integer
            .parseInt(PluginManager.getInstance().getFromSharedMem("imageHeight" + SessionID));
    ContentValues values = null;
    String resultOrientation = getFromSharedMem("frameorientation" + (i + 1) + Long.toString(SessionID));
    if (resultOrientation == null) {
        resultOrientation = getFromSharedMem("frameorientation" + i + Long.toString(SessionID));
    }

    String resultMirrored = getFromSharedMem("framemirrored" + (i + 1) + Long.toString(SessionID));
    if (resultMirrored == null) {
        resultMirrored = getFromSharedMem("framemirrored" + i + Long.toString(SessionID));
    }

    Boolean cameraMirrored = false;
    if (resultMirrored != null)
        cameraMirrored = Boolean.parseBoolean(resultMirrored);

    int mDisplayOrientation = 0;
    if (resultOrientation != null) {
        mDisplayOrientation = Integer.parseInt(resultOrientation);
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());
    boolean saveGeoInfo = prefs.getBoolean("useGeoTaggingPrefExport", false);

    DocumentFile file;
    DocumentFile saveDir = getSaveDirNew(false);
    if (saveDir == null || !saveDir.exists()) {
        return;
    }

    file = saveDir.createFile("image/jpeg", fileFormat);
    if (file == null || !file.canWrite()) {
        return;
    }

    OutputStream os = null;
    File bufFile = new File(ApplicationScreen.instance.getFilesDir(), "buffer.jpeg");
    try {
        os = new FileOutputStream(bufFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (os != null) {
        try {
            if (!isYUV) {
                os.write(buffer);
            } else {
                jpegQuality = Integer.parseInt(prefs.getString(MainScreen.sJPEGQualityPref, "95"));

                com.almalence.YuvImage image = new com.almalence.YuvImage(yuvBuffer, ImageFormat.NV21,
                        mImageWidth, mImageHeight, null);
                // to avoid problems with SKIA
                int cropHeight = image.getHeight() - image.getHeight() % 16;
                image.compressToJpeg(new Rect(0, 0, image.getWidth(), cropHeight), jpegQuality, os);
            }
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        mDisplayOrientation = saveExifToInput(bufFile, mDisplayOrientation, cameraMirrored, saveGeoInfo);

        // Copy buffer image with exif tags into result file.
        InputStream is = null;
        int len;
        byte[] buf = new byte[1024];
        try {
            os = ApplicationScreen.instance.getContentResolver().openOutputStream(file.getUri());
            is = new FileInputStream(bufFile);
            while ((len = is.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            is.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    bufFile.delete();

    values = new ContentValues();
    values.put(ImageColumns.TITLE, file.getName().substring(0, file.getName().lastIndexOf(".")));
    values.put(ImageColumns.DISPLAY_NAME, file.getName());
    values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
    values.put(ImageColumns.MIME_TYPE, "image/jpeg");
    values.put(ImageColumns.ORIENTATION, mDisplayOrientation);

    String filePath = file.getName();
    // If we able to get File object, than get path from it.
    // fileObject should not be null for files on phone memory.
    File fileObject = Util.getFileFromDocumentFile(file);
    if (fileObject != null) {
        filePath = fileObject.getAbsolutePath();
        values.put(ImageColumns.DATA, filePath);
    } else {
        // This case should typically happen for files saved to SD
        // card.
        String documentPath = Util.getAbsolutePathFromDocumentFile(file);
        values.put(ImageColumns.DATA, documentPath);
    }

    if (saveGeoInfo) {
        Location l = MLocation.getLocation(ApplicationScreen.getMainContext());
        if (l != null) {
            values.put(ImageColumns.LATITUDE, l.getLatitude());
            values.put(ImageColumns.LONGITUDE, l.getLongitude());
        }
    }

    ApplicationScreen.instance.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}

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

/**
 * Appends mp4 audio/video from {@code anotherFileDescriptor} to
 * {@code mainFileDescriptor}.//from   w  ww  .j av a  2s .co m
 */
public static DocumentFile appendNew(DocumentFile[] inputFiles) {
    try {
        DocumentFile targetFile = inputFiles[0];
        int[] inputFilesFds = new int[inputFiles.length];
        ArrayList<ParcelFileDescriptor> pfdsList = new ArrayList<ParcelFileDescriptor>();

        int i = 0;
        for (DocumentFile f : inputFiles) {
            ParcelFileDescriptor pfd = ApplicationScreen.instance.getContentResolver()
                    .openFileDescriptor(f.getUri(), "rw");
            pfdsList.add(pfd);
            inputFilesFds[i] = pfd.getFd();
            i++;
        }

        if (targetFile.exists() && targetFile.length() > 0) {
            String tmpFileName = targetFile.getName() + ".tmp";
            DocumentFile tmpTargetFile = targetFile.getParentFile().createFile("video/mp4", tmpFileName);
            ParcelFileDescriptor targetFilePfd = ApplicationScreen.instance.getContentResolver()
                    .openFileDescriptor(tmpTargetFile.getUri(), "rw");

            Mp4Editor.appendFds(inputFilesFds, targetFilePfd.getFd());

            targetFilePfd.close();
            for (ParcelFileDescriptor pfd : pfdsList) {
                pfd.close();
            }

            return tmpTargetFile;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}