List of usage examples for android.support.v4.provider DocumentFile createFile
public abstract DocumentFile createFile(String str, String str2);
From source file:freed.viewer.dngconvert.DngConvertingFragment.java
private void convertRawToDng(File file) { byte[] data = null; try {/*ww w. j a v a2s . c o m*/ data = RawToDng.readFile(file); Log.d("Main", "Filesize: " + data.length + " File:" + file.getAbsolutePath()); } catch (IOException ex) { ex.printStackTrace(); } String out = null; if (file.getName().endsWith(FileEnding.RAW)) out = file.getAbsolutePath().replace(FileEnding.RAW, FileEnding.DNG); if (file.getName().endsWith(FileEnding.BAYER)) out = file.getAbsolutePath().replace(FileEnding.BAYER, FileEnding.DNG); RawToDng dng = RawToDng.GetInstance(); String intsd = StringUtils.GetInternalSDCARD(); if (VERSION.SDK_INT <= VERSION_CODES.LOLLIPOP || file.getAbsolutePath().contains(intsd)) dng.setBayerData(data, out); else { DocumentFile df = ((ActivityInterface) getActivity()).getFreeDcamDocumentFolder(); DocumentFile wr = df.createFile("image/dng", file.getName().replace(FileEnding.JPG, FileEnding.DNG)); ParcelFileDescriptor pfd = null; try { pfd = getContext().getContentResolver().openFileDescriptor(wr.getUri(), "rw"); } catch (FileNotFoundException | IllegalArgumentException ex) { ex.printStackTrace(); } if (pfd != null) { dng.SetBayerDataFD(data, pfd, file.getName()); try { pfd.close(); } catch (IOException e) { e.printStackTrace(); } pfd = null; } } dng.setExifData(100, 0, 0, 0, 0, "", "0", 0); if (fakeGPS.isChecked()) dng.SetGpsData(Altitude, Latitude, Longitude, Provider, gpsTime); dng.WriteDngWithProfile(dngprofile); data = null; Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(file)); getActivity().sendBroadcast(intent); if (filesToConvert.length == 1) { final Bitmap map = new RawUtils().UnPackRAW(out); getActivity().runOnUiThread(new Runnable() { @Override public void run() { imageView.setImageBitmap(map); } }); } }
From source file:com.filemanager.free.filesystem.FileUtil.java
/** * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If the file is not * existing, it is created.// ww w . j a va 2 s .c o m * * @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; }
From source file:org.kde.kdeconnect.Plugins.SharePlugin.SharePlugin.java
@Override public boolean onPackageReceived(NetworkPackage np) { try {// w w w . j a v a 2s. co m if (np.hasPayload()) { Log.i("SharePlugin", "hasPayload"); final InputStream input = np.getPayload(); final long fileLength = np.getPayloadSize(); final String originalFilename = np.getString("filename", Long.toString(System.currentTimeMillis())); //We need to check for already existing files only when storing in the default path. //User-defined paths use the new Storage Access Framework that already handles this. final boolean customDestination = ShareSettingsActivity.isCustomDestinationEnabled(context); final String defaultPath = ShareSettingsActivity.getDefaultDestinationDirectory().getAbsolutePath(); final String filename = customDestination ? originalFilename : FilesHelper.findNonExistingNameForNewFile(defaultPath, originalFilename); String displayName = FilesHelper.getFileNameWithoutExt(filename); final String mimeType = FilesHelper.getMimeTypeFromFile(filename); if ("*/*".equals(mimeType)) { displayName = filename; } final DocumentFile destinationFolderDocument = ShareSettingsActivity .getDestinationDirectory(context); final DocumentFile destinationDocument = destinationFolderDocument.createFile(mimeType, displayName); final OutputStream destinationOutput = context.getContentResolver() .openOutputStream(destinationDocument.getUri()); final Uri destinationUri = destinationDocument.getUri(); final int notificationId = (int) System.currentTimeMillis(); Resources res = context.getResources(); final NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(res.getString(R.string.incoming_file_title, device.getName())) .setContentText(res.getString(R.string.incoming_file_text, filename)) .setTicker(res.getString(R.string.incoming_file_title, device.getName())) .setSmallIcon(android.R.drawable.stat_sys_download).setAutoCancel(true).setOngoing(true) .setProgress(100, 0, true); final NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build()); new Thread(new Runnable() { @Override public void run() { boolean successful = true; try { byte data[] = new byte[1024]; long progress = 0, prevProgressPercentage = 0; int count; while ((count = input.read(data)) >= 0) { progress += count; destinationOutput.write(data, 0, count); if (fileLength > 0) { if (progress >= fileLength) break; long progressPercentage = (progress * 100 / fileLength); if (progressPercentage != prevProgressPercentage) { prevProgressPercentage = progressPercentage; builder.setProgress(100, (int) progressPercentage, false); NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build()); } } //else Log.e("SharePlugin", "Infinite loop? :D"); } destinationOutput.flush(); } catch (Exception e) { successful = false; Log.e("SharePlugin", "Receiver thread exception"); e.printStackTrace(); } finally { try { destinationOutput.close(); } catch (Exception e) { } try { input.close(); } catch (Exception e) { } } try { Log.i("SharePlugin", "Transfer finished: " + destinationUri.getPath()); //Update the notification and allow to open the file from it Resources res = context.getResources(); String message = successful ? res.getString(R.string.received_file_title, device.getName()) : res.getString(R.string.received_file_fail_title, device.getName()); NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(message).setTicker(message) .setSmallIcon(android.R.drawable.stat_sys_download_done).setAutoCancel(true); if (successful) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(destinationUri, mimeType); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addNextIntent(intent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentText( res.getString(R.string.received_file_text, destinationDocument.getName())) .setContentIntent(resultPendingIntent); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean("share_notification_preference", true)) { builder.setDefaults(Notification.DEFAULT_ALL); } NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build()); if (successful) { if (!customDestination && Build.VERSION.SDK_INT >= 12) { Log.i("SharePlugin", "Adding to downloads"); DownloadManager manager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); manager.addCompletedDownload(destinationUri.getLastPathSegment(), device.getName(), true, mimeType, destinationUri.getPath(), fileLength, false); } else { //Make sure it is added to the Android Gallery anyway MediaStoreHelper.indexFile(context, destinationUri); } } } catch (Exception e) { Log.e("SharePlugin", "Receiver thread exception"); e.printStackTrace(); } } }).start(); } else if (np.has("text")) { Log.i("SharePlugin", "hasText"); String text = np.getString("text"); if (Build.VERSION.SDK_INT >= 11) { ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); cm.setText(text); } else { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text); } Toast.makeText(context, R.string.shareplugin_text_saved, Toast.LENGTH_LONG).show(); } else if (np.has("url")) { String url = np.getString("url"); Log.i("SharePlugin", "hasUrl: " + url); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (openUrlsDirectly) { context.startActivity(browserIntent); } else { Resources res = context.getResources(); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addNextIntent(browserIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); Notification noti = new NotificationCompat.Builder(context) .setContentTitle(res.getString(R.string.received_url_title, device.getName())) .setContentText(res.getString(R.string.received_url_text, url)) .setContentIntent(resultPendingIntent) .setTicker(res.getString(R.string.received_url_title, device.getName())) .setSmallIcon(R.drawable.ic_notification).setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL).build(); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); NotificationHelper.notifyCompat(notificationManager, (int) System.currentTimeMillis(), noti); } } else { Log.e("SharePlugin", "Error: Nothing attached!"); } } catch (Exception e) { Log.e("SharePlugin", "Exception"); e.printStackTrace(); } return true; }
From source file:com.anjalimacwan.MainActivity.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override/*from ww w . j a v a 2 s . c o m*/ public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (resultCode == RESULT_OK && resultData != null) { successful = true; if (requestCode == IMPORT) { Uri uri = resultData.getData(); ClipData clipData = resultData.getClipData(); if (uri != null) successful = importNote(uri); else if (clipData != null) for (int i = 0; i < clipData.getItemCount(); i++) { successful = importNote(clipData.getItemAt(i).getUri()); } // Show toast notification showToast(successful ? (uri == null ? R.string.notes_imported_successfully : R.string.note_imported_successfully) : R.string.error_importing_notes); // Send broadcast to NoteListFragment to refresh list of notes Intent listNotesIntent = new Intent(); listNotesIntent.setAction("com.anjalimacwan.LIST_NOTES"); LocalBroadcastManager.getInstance(this).sendBroadcast(listNotesIntent); } else if (requestCode == EXPORT) { try { saveExportedNote(loadNote(filesToExport[fileBeingExported].toString()), resultData.getData()); } catch (IOException e) { successful = false; } fileBeingExported++; if (fileBeingExported < filesToExport.length) reallyExportNote(); else showToast(successful ? (fileBeingExported == 1 ? R.string.note_exported_to : R.string.notes_exported_to) : R.string.error_exporting_notes); } else if (requestCode == EXPORT_TREE) { DocumentFile tree = DocumentFile.fromTreeUri(this, resultData.getData()); for (Object exportFilename : filesToExport) { try { DocumentFile file = tree.createFile("text/plain", generateFilename(loadNoteTitle(exportFilename.toString()))); saveExportedNote(loadNote(exportFilename.toString()), file.getUri()); } catch (IOException e) { successful = false; } } showToast(successful ? R.string.notes_exported_to : R.string.error_exporting_notes); } } }
From source file:org.totschnig.myexpenses.util.Utils.java
public static DocumentFile newFile(DocumentFile parentDir, String base, String mimeType, boolean addExtension) { int postfix = 0; do {//from w w w. j a v a 2 s . co m String name = base; if (postfix > 0) { name += "_" + postfix; } if (addExtension) { name += "." + mimeType.split("/")[1]; } if (parentDir.findFile(name) == null) { DocumentFile result = null; try { result = parentDir.createFile(mimeType, name); if (result == null) { AcraHelper.report(new Exception( String.format("createFile returned null: mimeType %s; name %s; parent %s", mimeType, name, parentDir.getUri().toString()))); } } catch (SecurityException e) { AcraHelper.report(new Exception( String.format("createFile threw SecurityException: mimeType %s; name %s; parent %s", mimeType, name, parentDir.getUri().toString()))); } return result; } postfix++; } while (true); }
From source file:com.farmerbb.notepad.activity.MainActivity.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override/*www .j a va 2s. c o m*/ public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (resultCode == RESULT_OK && resultData != null) { successful = true; if (requestCode == IMPORT) { Uri uri = resultData.getData(); ClipData clipData = resultData.getClipData(); if (uri != null) successful = importNote(uri); else if (clipData != null) for (int i = 0; i < clipData.getItemCount(); i++) { successful = importNote(clipData.getItemAt(i).getUri()); } // Show toast notification showToast(successful ? (uri == null ? R.string.notes_imported_successfully : R.string.note_imported_successfully) : R.string.error_importing_notes); // Send broadcast to NoteListFragment to refresh list of notes Intent listNotesIntent = new Intent(); listNotesIntent.setAction("com.farmerbb.notepad.LIST_NOTES"); LocalBroadcastManager.getInstance(this).sendBroadcast(listNotesIntent); } else if (requestCode == EXPORT) { try { saveExportedNote(loadNote(filesToExport[fileBeingExported].toString()), resultData.getData()); } catch (IOException e) { successful = false; } fileBeingExported++; if (fileBeingExported < filesToExport.length) reallyExportNotes(); else showToast(successful ? (fileBeingExported == 1 ? R.string.note_exported_to : R.string.notes_exported_to) : R.string.error_exporting_notes); File fileToDelete = new File(getFilesDir() + File.separator + "exported_note"); fileToDelete.delete(); } else if (requestCode == EXPORT_TREE) { DocumentFile tree = DocumentFile.fromTreeUri(this, resultData.getData()); for (Object exportFilename : filesToExport) { try { DocumentFile file = tree.createFile("text/plain", generateFilename(loadNoteTitle(exportFilename.toString()))); if (file != null) saveExportedNote(loadNote(exportFilename.toString()), file.getUri()); else successful = false; } catch (IOException e) { successful = false; } } showToast(successful ? R.string.notes_exported_to : R.string.error_exporting_notes); } } }
From source file:freed.cam.apis.camera2.modules.PictureModuleApi2.java
@NonNull private void process_rawSensor(ImageHolder image, File file) { Log.d(TAG, "Create DNG"); DngCreator dngCreator = new DngCreator(cameraHolder.characteristics, image.getCaptureResult()); //Orientation 90 is not a valid EXIF orientation value, fuck off that is valid! try {/* w w w.ja v a2 s . c o m*/ dngCreator.setOrientation(image.captureResult.get(CaptureResult.JPEG_ORIENTATION)); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } if (appSettingsManager.getApiString(AppSettingsManager.SETTING_LOCATION).equals(KEYS.ON)) dngCreator .setLocation(cameraUiWrapper.getActivityInterface().getLocationHandler().getCurrentLocation()); try { if (!appSettingsManager.GetWriteExternal()) dngCreator.writeImage(new FileOutputStream(file), image.getImage()); else { DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder(); DocumentFile wr = df.createFile("image/*", file.getName()); dngCreator.writeImage( cameraUiWrapper.getContext().getContentResolver().openOutputStream(wr.getUri()), image.getImage()); } cameraUiWrapper.getActivityInterface().ScanFile(file); } catch (IOException ex) { ex.printStackTrace(); } image.getImage().close(); image = null; }
From source file:com.osama.cryptofm.tasks.MoveTask.java
private void move(File f) throws Exception { if (f.isDirectory()) { //check if destination folder is in external sdcard if (FileUtils.isDocumentFile(mDestinationFolder)) { DocumentFile rootDocumentFile = FileDocumentUtils.getDocumentFile(new File(mDestinationFolder)); rootDocumentFile.createDirectory(f.getName()); } else {/*from www.jav a 2 s . c o m*/ //create folder in the destination mDestinationFolder = mDestinationFolder + f.getName() + "/"; File tmp = new File(mDestinationFolder); if (!tmp.exists()) { tmp.mkdir(); } else { return; } } Log.d(TAG, "move: File is a directory"); for (File file : f.listFiles()) { move(file); } } else { Log.d(TAG, "move: Moving file: " + f.getName()); Log.d(TAG, "move: Destination folder is: " + mDestinationFolder); isNextFile = true; publishProgress(f.getName()); publishProgress("" + 0); if (FileUtils.isDocumentFile(mDestinationFolder)) { DocumentFile dest = rootDocumentFile.createFile(FileUtils.getExtension(f.getName()), f.getName()); innerMove(new BufferedInputStream(new FileInputStream(f)), CryptoFM.getContext().getContentResolver().openOutputStream(dest.getUri()), f.length()); } else { //check if file already exits File destinationFile = new File(mDestinationFolder + f.getName()); if (destinationFile.exists()) { return; } innerMove(new BufferedInputStream(new FileInputStream(f)), new BufferedOutputStream(new FileOutputStream(destinationFile)), f.length()); } } //delete the input file //if copying then don't if (SharedData.IS_COPYING_NOT_MOVING) { return; } if (!f.delete()) { throw new IOException("cannot move files"); } }
From source file:com.almalence.opencam.PluginManagerBase.java
private void saveInputFileNew(boolean isYUV, Long SessionID, int i, byte[] buffer, int yuvBuffer, String fileFormat) {/*from w w w . j ava 2 s . co 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
@TargetApi(19) private static DocumentFile getOutputMediaDocumentFile() { DocumentFile saveDir = PluginManager.getSaveDirNew(false); if (saveDir == null || !saveDir.exists() || !saveDir.canWrite()) { saveDir = PluginManager.getSaveDirNew(true); }/* w w w . j a va 2 s. 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; }