/** * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If * the file is not existing, it is created. * * @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; }
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(); } // 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; }