List of usage examples for android.support.v4.provider DocumentFile createFile
public abstract DocumentFile createFile(String str, String str2);
From source file:de.arcus.playmusiclib.PlayMusicManager.java
/** * Exports a track to the sd card//from w w w . ja v a 2 s .c om * @param musicTrack The music track you want to export * @param uri The document tree * @return Returns whether the export was successful */ public boolean exportMusicTrack(MusicTrack musicTrack, Uri uri, String path) { // Check for null if (musicTrack == null) return false; String srcFile = musicTrack.getSourceFile(); // Could not find the source file if (srcFile == null) return false; String fileTmp = getTempPath() + "/tmp.mp3"; // Copy to temp path failed if (!SuperUserTools.fileCopy(srcFile, fileTmp)) return false; // Encrypt the file if (musicTrack.isEncoded()) { String fileTmpCrypt = getTempPath() + "/crypt.mp3"; // Encrypts the file if (trackEncrypt(musicTrack, fileTmp, fileTmpCrypt)) { // Remove the old tmp file FileTools.fileDelete(fileTmp); // New tmp file fileTmp = fileTmpCrypt; } else { Logger.getInstance().logWarning("ExportMusicTrack", "Encrypting failed! Continue with decrypted file."); } } String dest; Uri copyUri = null; if (uri.toString().startsWith("file://")) { // Build the full path dest = uri.buildUpon().appendPath(path).build().getPath(); String parentDirectory = new File(dest).getParent(); FileTools.directoryCreate(parentDirectory); } else { // Complex uri (Lollipop) dest = getTempPath() + "/final.mp3"; // The root DocumentFile document = DocumentFile.fromTreeUri(mContext, uri); // Creates the subdirectories String[] directories = path.split("\\/"); for (int i = 0; i < directories.length - 1; i++) { String directoryName = directories[i]; boolean found = false; // Search all sub elements for (DocumentFile subDocument : document.listFiles()) { // Directory exists if (subDocument.isDirectory() && subDocument.getName().equals(directoryName)) { document = subDocument; found = true; break; } } if (!found) { // Create the directory document = document.createDirectory(directoryName); } } // Gets the filename String filename = directories[directories.length - 1]; for (DocumentFile subDocument : document.listFiles()) { // Directory exists if (subDocument.isFile() && subDocument.getName().equals(filename)) { // Delete the file subDocument.delete(); break; } } // Create the mp3 file document = document.createFile("music/mp3", filename); // Create the directories copyUri = document.getUri(); } // We want to export the ID3 tags if (mID3Enable) { // Adds the meta data if (!trackWriteID3(musicTrack, fileTmp, dest)) { Logger.getInstance().logWarning("ExportMusicTrack", "ID3 writer failed! Continue without ID3 tags."); // Failed, moving without meta data if (!FileTools.fileMove(fileTmp, dest)) { Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!"); // Could not copy the file return false; } } } else { // Moving the file if (!FileTools.fileMove(fileTmp, dest)) { Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!"); // Could not copy the file return false; } } // We need to copy the file to a uri if (copyUri != null) { // Lollipop only if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { // Gets the file descriptor ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver() .openFileDescriptor(copyUri, "w"); // Gets the output stream FileOutputStream fileOutputStream = new FileOutputStream( parcelFileDescriptor.getFileDescriptor()); // Gets the input stream FileInputStream fileInputStream = new FileInputStream(dest); // Copy the stream FileTools.fileCopy(fileInputStream, fileOutputStream); // Close all streams fileOutputStream.close(); fileInputStream.close(); parcelFileDescriptor.close(); } catch (FileNotFoundException e) { Logger.getInstance().logError("ExportMusicTrack", "File not found!"); // Could not copy the file return false; } catch (IOException e) { Logger.getInstance().logError("ExportMusicTrack", "Failed to write the document: " + e.toString()); // Could not copy the file return false; } } } // Delete temp files cleanUp(); // Adds the file to the media system //new MediaScanner(mContext, dest); // Done return true; }
From source file:com.almalence.opencam.SavingService.java
public void saveResultPictureNew(long sessionID) { if (ApplicationScreen.getForceFilename() != null) { saveResultPicture(sessionID);/*from ww w .j ava2s . c om*/ return; } initSavingPrefs(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // save fused result try { DocumentFile saveDir = getSaveDirNew(false); int imagesAmount = Integer .parseInt(getFromSharedMem("amountofresultframes" + Long.toString(sessionID))); if (imagesAmount == 0) imagesAmount = 1; int imageIndex = 0; String sImageIndex = getFromSharedMem("resultframeindex" + Long.toString(sessionID)); if (sImageIndex != null) imageIndex = Integer.parseInt(getFromSharedMem("resultframeindex" + Long.toString(sessionID))); if (imageIndex != 0) imagesAmount = 1; ContentValues values = null; boolean hasDNGResult = false; for (int i = 1; i <= imagesAmount; i++) { hasDNGResult = false; String format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID)); if (format != null && format.equalsIgnoreCase("dng")) hasDNGResult = true; String idx = ""; if (imagesAmount != 1) idx += "_" + ((format != null && !format.equalsIgnoreCase("dng") && hasDNGResult) ? i - imagesAmount / 2 : i); String modeName = getFromSharedMem("modeSaveName" + Long.toString(sessionID)); // define file name format. from settings! String fileFormat = getExportFileName(modeName); fileFormat += idx; DocumentFile file = null; if (ApplicationScreen.getForceFilename() == null) { if (hasDNGResult) { file = saveDir.createFile("image/x-adobe-dng", fileFormat + ".dng"); } else { file = saveDir.createFile("image/jpeg", fileFormat); } } else { file = DocumentFile.fromFile(ApplicationScreen.getForceFilename()); } // Create buffer image to deal with exif tags. OutputStream os = null; File bufFile = new File(getApplicationContext().getFilesDir(), "buffer.jpeg"); try { os = new FileOutputStream(bufFile); } catch (Exception e) { e.printStackTrace(); } // Take only one result frame from several results // Used for PreShot plugin that may decide which result to save if (imagesAmount == 1 && imageIndex != 0) { i = imageIndex; //With changed frame index we have to get appropriate frame format format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID)); } String resultOrientation = getFromSharedMem( "resultframeorientation" + i + Long.toString(sessionID)); int orientation = 0; if (resultOrientation != null) orientation = Integer.parseInt(resultOrientation); String resultMirrored = getFromSharedMem("resultframemirrored" + i + Long.toString(sessionID)); Boolean cameraMirrored = false; if (resultMirrored != null) cameraMirrored = Boolean.parseBoolean(resultMirrored); int x = Integer.parseInt(getFromSharedMem("saveImageHeight" + Long.toString(sessionID))); int y = Integer.parseInt(getFromSharedMem("saveImageWidth" + Long.toString(sessionID))); if (orientation == 0 || orientation == 180 || (format != null && format.equalsIgnoreCase("dng"))) { x = Integer.valueOf(getFromSharedMem("saveImageWidth" + Long.toString(sessionID))); y = Integer.valueOf(getFromSharedMem("saveImageHeight" + Long.toString(sessionID))); } Boolean writeOrientationTag = true; String writeOrientTag = getFromSharedMem("writeorientationtag" + Long.toString(sessionID)); if (writeOrientTag != null) writeOrientationTag = Boolean.parseBoolean(writeOrientTag); if (format != null && format.equalsIgnoreCase("jpeg")) {// if result in jpeg format if (os != null) { byte[] frame = SwapHeap.SwapFromHeap( Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID))), Integer.parseInt( getFromSharedMem("resultframelen" + i + Long.toString(sessionID)))); os.write(frame); try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } else if (format != null && format.equalsIgnoreCase("dng") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { saveDNGPicture(i, sessionID, os, x, y, orientation, cameraMirrored); } else {// if result in nv21 format int yuv = Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID))); com.almalence.YuvImage out = new com.almalence.YuvImage(yuv, ImageFormat.NV21, x, y, null); Rect r; String res = getFromSharedMem("resultfromshared" + Long.toString(sessionID)); if ((null == res) || "".equals(res) || "true".equals(res)) { // to avoid problems with SKIA int cropHeight = out.getHeight() - out.getHeight() % 16; r = new Rect(0, 0, out.getWidth(), cropHeight); } else { if (null == getFromSharedMem("resultcrop0" + Long.toString(sessionID))) { // to avoid problems with SKIA int cropHeight = out.getHeight() - out.getHeight() % 16; r = new Rect(0, 0, out.getWidth(), cropHeight); } else { int crop0 = Integer .parseInt(getFromSharedMem("resultcrop0" + Long.toString(sessionID))); int crop1 = Integer .parseInt(getFromSharedMem("resultcrop1" + Long.toString(sessionID))); int crop2 = Integer .parseInt(getFromSharedMem("resultcrop2" + Long.toString(sessionID))); int crop3 = Integer .parseInt(getFromSharedMem("resultcrop3" + Long.toString(sessionID))); r = new Rect(crop0, crop1, crop0 + crop2, crop1 + crop3); } } jpegQuality = Integer.parseInt(prefs.getString(ApplicationScreen.sJPEGQualityPref, "95")); if (!out.compressToJpeg(r, jpegQuality, os)) { ApplicationScreen.getMessageHandler() .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION); return; } SwapHeap.FreeFromHeap(yuv); } String orientation_tag = String.valueOf(0); // int sensorOrientation = CameraController.getSensorOrientation(CameraController.getCameraIndex()); // int displayOrientation = CameraController.getDisplayOrientation(); //// sensorOrientation = (360 + sensorOrientation + (cameraMirrored ? -displayOrientation //// : displayOrientation)) % 360; // if (cameraMirrored) displayOrientation = -displayOrientation; // // // Calculate desired JPEG orientation relative to camera orientation to make // // the image upright relative to the device orientation // orientation = (sensorOrientation + displayOrientation + 360) % 360; switch (orientation) { default: case 0: orientation_tag = String.valueOf(0); break; case 90: orientation_tag = cameraMirrored ? String.valueOf(270) : String.valueOf(90); break; case 180: orientation_tag = String.valueOf(180); break; case 270: orientation_tag = cameraMirrored ? String.valueOf(90) : String.valueOf(270); break; } int exif_orientation = ExifInterface.ORIENTATION_NORMAL; if (writeOrientationTag) { switch ((orientation + 360) % 360) { default: case 0: exif_orientation = ExifInterface.ORIENTATION_NORMAL; break; case 90: exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270 : ExifInterface.ORIENTATION_ROTATE_90; break; case 180: exif_orientation = ExifInterface.ORIENTATION_ROTATE_180; break; case 270: exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90 : ExifInterface.ORIENTATION_ROTATE_270; break; } } else { switch ((additionalRotationValue + 360) % 360) { default: case 0: exif_orientation = ExifInterface.ORIENTATION_NORMAL; break; case 90: exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270 : ExifInterface.ORIENTATION_ROTATE_90; break; case 180: exif_orientation = ExifInterface.ORIENTATION_ROTATE_180; break; case 270: exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90 : ExifInterface.ORIENTATION_ROTATE_270; break; } } if (!enableExifTagOrientation) exif_orientation = ExifInterface.ORIENTATION_NORMAL; values = new ContentValues(); values.put(ImageColumns.TITLE, file.getName().substring(0, file.getName().lastIndexOf(".") >= 0 ? file.getName().lastIndexOf(".") : file.getName().length())); values.put(ImageColumns.DISPLAY_NAME, file.getName()); values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis()); values.put(ImageColumns.MIME_TYPE, "image/jpeg"); if (enableExifTagOrientation) { if (writeOrientationTag) { values.put(ImageColumns.ORIENTATION, String.valueOf( (Integer.parseInt(orientation_tag) + additionalRotationValue + 360) % 360)); } else { values.put(ImageColumns.ORIENTATION, String.valueOf((additionalRotationValue + 360) % 360)); } } else { values.put(ImageColumns.ORIENTATION, String.valueOf(0)); } 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 (!enableExifTagOrientation && !hasDNGResult) { Matrix matrix = new Matrix(); if (writeOrientationTag && (orientation + additionalRotationValue) != 0) { matrix.postRotate((orientation + additionalRotationValue + 360) % 360); rotateImage(bufFile, matrix); } else if (!writeOrientationTag && additionalRotationValue != 0) { matrix.postRotate((additionalRotationValue + 360) % 360); rotateImage(bufFile, matrix); } } if (useGeoTaggingPrefExport) { Location l = MLocation.getLocation(getApplicationContext()); if (l != null) { double lat = l.getLatitude(); double lon = l.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { values.put(ImageColumns.LATITUDE, l.getLatitude()); values.put(ImageColumns.LONGITUDE, l.getLongitude()); } } } File modifiedFile = null; if (!hasDNGResult) { modifiedFile = saveExifTags(bufFile, sessionID, i, x, y, exif_orientation, useGeoTaggingPrefExport, enableExifTagOrientation); } if (modifiedFile != null) { bufFile.delete(); if (ApplicationScreen.getForceFilename() == null) { // Copy buffer image with exif tags into result file. InputStream is = null; int len; byte[] buf = new byte[4096]; try { os = getApplicationContext().getContentResolver().openOutputStream(file.getUri()); is = new FileInputStream(modifiedFile); while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } is.close(); os.close(); } catch (IOException eIO) { eIO.printStackTrace(); final IOException eIOFinal = eIO; ApplicationScreen.instance.runOnUiThread(new Runnable() { public void run() { Toast.makeText(MainScreen.getMainContext(), "Error ocurred:" + eIOFinal.getLocalizedMessage(), Toast.LENGTH_LONG) .show(); } }); } catch (Exception e) { e.printStackTrace(); } } else { copyToForceFileName(modifiedFile); } modifiedFile.delete(); } else { // Copy buffer image into result file. InputStream is = null; int len; byte[] buf = new byte[4096]; try { os = getApplicationContext().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(); } Uri uri = getApplicationContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); broadcastNewPicture(uri); } ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED); } catch (IOException e) { e.printStackTrace(); ApplicationScreen.getMessageHandler() .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION); return; } catch (Exception e) { e.printStackTrace(); ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED); } }