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

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

Introduction

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

Prototype

public abstract DocumentFile createFile(String str, String str2);

Source Link

Usage

From source file:com.osama.cryptofm.utils.FileDocumentUtils.java

public static DocumentFile getDocumentFile(final File file) {

    String baseFolder = SharedData.EXTERNAL_SDCARD_ROOT_PATH;
    boolean isDirectory = file.isDirectory();

    String relativePath = null;//from   w  w w.j  av  a2  s  .com
    try {
        Log.d(TAG, "getDocumentFile: basefolder:file" + baseFolder + " : " + file.getAbsolutePath());
        String fullPath = file.getCanonicalPath();
        if ((file.getAbsolutePath() + "/").equals(baseFolder)) {
            Log.d(TAG, "getDocumentFile: uri is: " + SharedData.EXT_ROOT_URI);
            return DocumentFile.fromTreeUri(CryptoFM.getContext(), Uri.parse(SharedData.EXT_ROOT_URI));
        } else {

            relativePath = fullPath.substring(baseFolder.length());
        }
    } catch (IOException e) {
        return null;
    }

    Uri treeUri = Uri.parse(SharedData.EXT_ROOT_URI);

    if (treeUri == null) {
        return null;
    }
    relativePath = relativePath.replace(SharedData.EXTERNAL_SDCARD_ROOT_PATH, "");
    // start with root of SD card and then parse through document tree.
    Log.d(TAG, "getDocumentFile: relative path is: " + relativePath);
    DocumentFile document = DocumentFile.fromTreeUri(CryptoFM.getContext(), treeUri);

    String[] parts = relativePath.split("\\/");
    for (int i = 0; i < parts.length; i++) {
        DocumentFile nextDocument = document.findFile(parts[i]);
        Log.d(TAG, "getDocumentFile: next document is:  " + parts[i]);
        if (nextDocument == null) {
            if ((i < parts.length - 1) || isDirectory) {
                Log.d(TAG, "getDocumentFile: creating next directory");
                nextDocument = document.createDirectory(parts[i]);
            } else {
                nextDocument = document.createFile("image", parts[i]);
            }
        }
        document = nextDocument;
    }
    Log.d(TAG, "getDocumentFile: file uri is: " + document.getUri());
    return document;
}

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

public static boolean mkfile(final File file, Context context) throws IOException {
    if (file == null)
        return false;
    if (file.exists()) {
        // nothing to create.
        return !file.isDirectory();
    }//from   w  ww .j  av  a 2s.  co  m

    // Try the normal way
    try {
        if (file.createNewFile()) {
            return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    boolean b = true;
    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && FileUtil.isOnExtSdCard(file, context)) {
        DocumentFile document = getDocumentFile(file.getParentFile(), true, context);
        // getDocumentFile implicitly creates the directory.
        try {
            b = document.createFile(MimeTypes.getMimeType(file), file.getName()) != null;
            return b;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        try {
            return MediaStoreHack.mkfile(context, file);
        } catch (Exception e) {
            return false;
        }
    }
    return false;
}

From source file:freed.cam.apis.sonyremote.modules.PictureModuleSony.java

@Override
public void onPictureTaken(URL url) {
    File file = new File(cameraUiWrapper.getActivityInterface().getStorageHandler()
            .getNewFilePath(appSettingsManager.GetWriteExternal(), ".jpg"));
    try {/* ww  w  . j a  v a  2  s.  c o  m*/
        file.createNewFile();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    InputStream inputStream = null;
    OutputStream output = null;
    try {
        inputStream = new BufferedInputStream(url.openStream());
        if (VERSION.SDK_INT <= VERSION_CODES.LOLLIPOP
                || VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && !appSettingsManager.GetWriteExternal())
            output = new FileOutputStream(file);
        else {
            DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder();
            DocumentFile wr = df.createFile("image/jpeg", file.getName());
            output = cameraUiWrapper.getContext().getContentResolver().openOutputStream(wr.getUri());
        }
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        try {
            if (output != null)
                output.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    cameraUiWrapper.getActivityInterface().ScanFile(file);
    fireOnWorkFinish(file);

}

From source file:freed.viewer.stack.StackActivity.java

private void saveBitmapToFile(Bitmap bitmap, File file) {
    OutputStream outStream = null;
    String intsd = StringUtils.GetInternalSDCARD();

    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP || file.getAbsolutePath().contains(intsd)
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        try {//from w ww .  j  a v  a  2  s.  c o m
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        DocumentFile df = getFreeDcamDocumentFolder();

        DocumentFile wr = df.createFile("image/*", file.getName());
        try {
            outStream = getContentResolver().openOutputStream(wr.getUri());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    MediaScannerManager.ScanMedia(getContext(), file);
}

From source file:freed.cam.apis.camera1.modules.AbstractVideoModule.java

protected void setRecorderOutPutFile(String s) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT
            || !appSettingsManager.GetWriteExternal() && VERSION.SDK_INT >= VERSION_CODES.KITKAT)
        recorder.setOutputFile(s);//from ww  w . ja v a  2 s .  co m
    else {
        File f = new File(s);
        DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder();
        DocumentFile wr = df.createFile("*/*", f.getName());
        try {
            fileDescriptor = cameraUiWrapper.getContext().getContentResolver().openFileDescriptor(wr.getUri(),
                    "rw");
            recorder.setOutputFile(fileDescriptor.getFileDescriptor());
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            try {
                fileDescriptor.close();
            } catch (IOException ex1) {
                ex1.printStackTrace();
            }
        }
    }

}

From source file:org.dkf.jed2k.android.LollipopFileSystem.java

private static DocumentFile getFile(Context context, File file, boolean create) {
    try {/*from   ww w .  j  a v  a  2 s. c  o m*/
        String path = file.getAbsolutePath();
        File parent = file.getParentFile();
        if (parent == null) {
            return DocumentFile.fromFile(file);
        }

        DocumentFile f = getDirectory(context, parent, false);
        if (f == null && create) {
            f = getDirectory(context, parent, create);
        }

        if (f != null) {
            String name = file.getName();
            DocumentFile child = f.findFile(name);
            if (child != null) {
                if (child.isFile()) {
                    f = child;
                } else {
                    f = null;
                }
            } else {
                if (create) {
                    f = f.createFile("application/octet-stream", name);
                } else {
                    f = null;
                }
            }
        }

        return f;
    } catch (Exception e) {
        LOG.error("Error getting file: {} {}", file, e);
        return null;
    }
}

From source file:com.theelix.libreexplorer.FileManager.java

public static void createDestFiles(DocumentFile folder) throws IOException, FileNotCreatedException {
    ArrayList<String> destFiles = new ArrayList<>();
    for (File selectedFile : selectedFiles) {
        String origFileName;/* w w w.  ja  va2 s . c o m*/
        String extension;
        try {
            origFileName = selectedFile.getName().substring(0, selectedFile.getName().lastIndexOf("."));
        } catch (IndexOutOfBoundsException e) {
            origFileName = selectedFile.getName();
        }
        String fileName = selectedFile.getName();
        try {
            extension = fileName.substring(fileName.lastIndexOf("."));
        } catch (IndexOutOfBoundsException e) {
            extension = "";
        }
        int lastIndex = 1;
        while (new File(getCurrentDirectory() + File.separator + fileName).exists()) {
            fileName = origFileName + " (" + lastIndex + ")" + extension;
            lastIndex++;
        }
        if (selectedFile.isDirectory()) {
            folder.createDirectory(fileName);
        } else {
            folder.createFile(FileUtilties.getMimeType(selectedFile), fileName);
        }
        destFiles.add(fileName);
    }
    FileManager.destFiles = destFiles.toArray(new String[destFiles.size()]);
    PasteTask task = new PasteTask(mContext);
    task.execute();

}

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

private static DocumentFile getFile(Context context, File file, boolean create) {
    try {// www.j  a  v  a2  s.  c  om
        String path = file.getAbsolutePath();
        DocumentFile cached = CACHE.get(path);
        if (cached != null && cached.isFile()) {
            return cached;
        }

        File parent = file.getParentFile();
        if (parent == null) {
            return DocumentFile.fromFile(file);
        }

        DocumentFile f = getDirectory(context, parent, false);
        if (f == null && create) {
            f = getDirectory(context, parent, create);
        }

        if (f != null) {
            String name = file.getName();
            DocumentFile child = f.findFile(name);
            if (child != null) {
                if (child.isFile()) {
                    f = child;
                } else {
                    f = null;
                }
            } else {
                if (create) {
                    f = f.createFile("application/octet-stream", name);
                } else {
                    f = null;
                }
            }
        }

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

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

From source file:freed.cam.apis.camera2.modules.VideoModuleApi2.java

private void setRecorderFilePath() {
    if (!appSettingsManager.GetWriteExternal()) {
        mediaRecorder.setOutputFile(recordingFile.getAbsolutePath());
    } else {//from w w  w. ja  v  a 2  s .c om
        Uri uri = Uri.parse(appSettingsManager.GetBaseFolder());
        DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder();
        DocumentFile wr = df.createFile("*/*", recordingFile.getName());
        ParcelFileDescriptor fileDescriptor = null;
        try {
            fileDescriptor = cameraUiWrapper.getContext().getContentResolver().openFileDescriptor(wr.getUri(),
                    "rw");
            mediaRecorder.setOutputFile(fileDescriptor.getFileDescriptor());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            try {
                fileDescriptor.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

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++;/*w  w w  . java 2 s  . 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();
            }
        }
    }
}