/** * 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. */ 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; }
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; }
public static OutputStream getOutputStream(@NonNull final File target, Context context, long s) { OutputStream outStream = null; try { // First try the normal way if (isWritable(target)) { // standard way outStream = new FileOutputStream(target); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // Storage Access Framework DocumentFile targetDocument = getDocumentFile(target, false, context); outStream = context.getContentResolver().openOutputStream(targetDocument.getUri()); } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { // Workaround for Kitkat ext SD card return MediaStoreHack.getOutputStream(context, target, s); } } } catch (Exception e) { Log.e("AmazeFileUtils", "Error when copying file from " + target.getAbsolutePath(), e); } return outStream; }