Example usage for android.content ContentResolver openOutputStream

List of usage examples for android.content ContentResolver openOutputStream

Introduction

In this page you can find the example usage for android.content ContentResolver openOutputStream.

Prototype

public final @Nullable OutputStream openOutputStream(@NonNull Uri uri) throws FileNotFoundException 

Source Link

Document

Synonym for #openOutputStream(Uri,String) openOutputStream(uri, "w") .

Usage

From source file:com.nextgis.ngm_clink_monitoring.fragments.ObjectStatusFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    File tempPhotoFile = new File(mTempPhotoPath);

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        GISApplication app = (GISApplication) getActivity().getApplication();
        ContentResolver contentResolver = app.getContentResolver();
        String photoFileName = getPhotoFileName();

        try {/*w  ww.  j a v  a2  s . co  m*/
            BitmapUtil.writeLocationToExif(tempPhotoFile, app.getCurrentLocation(), 0);
        } catch (IOException e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName
                + "/" + mObjectId + "/attach");

        ContentValues values = new ContentValues();
        values.put(VectorLayer.ATTACH_DISPLAY_NAME, photoFileName);
        values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg");
        //values.put(VectorLayer.ATTACH_DESCRIPTION, photoFileName);

        Uri attachUri = null;
        try {
            attachUri = contentResolver.insert(allAttachesUri, values);

        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        if (null != attachUri) {

            try {
                int exifOrientation = BitmapUtil.getOrientationFromExif(tempPhotoFile);

                // resize and rotate
                Bitmap sourceBitmap = BitmapFactory.decodeFile(tempPhotoFile.getPath());
                Bitmap resizedBitmap = BitmapUtil.getResizedBitmap(sourceBitmap,
                        FoclConstants.PHOTO_MAX_SIZE_PX, FoclConstants.PHOTO_MAX_SIZE_PX);
                Bitmap rotatedBitmap = BitmapUtil.rotateBitmap(resizedBitmap, exifOrientation);

                // jpeg compress
                File tempAttachFile = File.createTempFile("attach", null, app.getCacheDir());
                OutputStream tempOutStream = new FileOutputStream(tempAttachFile);
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, FoclConstants.PHOTO_JPEG_COMPRESS_QUALITY,
                        tempOutStream);
                tempOutStream.close();

                int newHeight = rotatedBitmap.getHeight();
                int newWidth = rotatedBitmap.getWidth();

                rotatedBitmap.recycle();

                // write EXIF to new file
                BitmapUtil.copyExifData(tempPhotoFile, tempAttachFile);

                ExifInterface attachExif = new ExifInterface(tempAttachFile.getCanonicalPath());

                attachExif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL);
                attachExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, "" + newHeight);
                attachExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, "" + newWidth);

                attachExif.saveAttributes();

                // attach data from tempAttachFile
                OutputStream attachOutStream = contentResolver.openOutputStream(attachUri);
                FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream);
                attachOutStream.close();

                tempAttachFile.delete();

            } catch (IOException e) {
                Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }

            Log.d(TAG, attachUri.toString());

        } else {
            Log.d(TAG, "insert attach failed");
        }

        try {
            if (app.isOriginalPhotoSaving()) {
                File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName);

                if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) {
                    Toast.makeText(getActivity(), "Save original photo failed", Toast.LENGTH_LONG).show();
                }

            } else {
                tempPhotoFile.delete();
            }

            setPhotoGalleryAdapter();
            setPhotoGalleryVisibility(true);

        } catch (IOException e) {
            Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_CANCELED) {
        tempPhotoFile.delete();
    }
}

From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java

/**
 * Starts copy of file//from w ww . j a  v  a2 s .c om
 * Supports : {@link File}, {@link jcifs.smb.SmbFile}, {@link DocumentFile}, {@link CloudStorage}
 * @param lowOnMemory defines whether system is running low on memory, in which case we'll switch to
 *                    using streams instead of channel which maps the who buffer in memory.
 *                    TODO: Use buffers even on low memory but don't map the whole file to memory but
 *                          parts of it, and transfer each part instead.
 */
private void startCopy(boolean lowOnMemory) throws IOException {

    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    BufferedInputStream bufferedInputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    try {

        // initializing the input channels based on file types
        if (mSourceFile.isOtgFile()) {
            // source is in otg
            ContentResolver contentResolver = mContext.getContentResolver();
            DocumentFile documentSourceFile = OTGUtil.getDocumentFile(mSourceFile.getPath(), mContext, false);

            bufferedInputStream = new BufferedInputStream(
                    contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isSmb()) {

            // source is in smb
            bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(), DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isSftp()) {
            bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mSourceFile.isDropBoxFile()) {

            CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageDropbox.download(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath())));
        } else if (mSourceFile.isBoxFile()) {

            CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageBox.download(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath())));
        } else if (mSourceFile.isGoogleDriveFile()) {

            CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
            bufferedInputStream = new BufferedInputStream(
                    cloudStorageGdrive.download(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath())));
        } else if (mSourceFile.isOneDriveFile()) {

            CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
            bufferedInputStream = new BufferedInputStream(cloudStorageOnedrive
                    .download(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath())));
        } else {

            // source file is neither smb nor otg; getting a channel from direct file instead of stream
            File file = new File(mSourceFile.getPath());
            if (FileUtil.isReadable(file)) {

                if (mTargetFile.isOneDriveFile() || mTargetFile.isDropBoxFile()
                        || mTargetFile.isGoogleDriveFile() || mTargetFile.isBoxFile() || lowOnMemory) {
                    // our target is cloud, we need a stream not channel
                    bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
                } else {

                    inChannel = new RandomAccessFile(file, "r").getChannel();
                }
            } else {
                ContentResolver contentResolver = mContext.getContentResolver();
                DocumentFile documentSourceFile = FileUtil.getDocumentFile(file, mSourceFile.isDirectory(),
                        mContext);

                bufferedInputStream = new BufferedInputStream(
                        contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE);
            }
        }

        // initializing the output channels based on file types
        if (mTargetFile.isOtgFile()) {

            // target in OTG, obtain streams from DocumentFile Uri's

            ContentResolver contentResolver = mContext.getContentResolver();
            DocumentFile documentTargetFile = OTGUtil.getDocumentFile(mTargetFile.getPath(), mContext, true);

            bufferedOutputStream = new BufferedOutputStream(
                    contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isSftp()) {
            bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isSmb()) {

            bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext),
                    DEFAULT_BUFFER_SIZE);
        } else if (mTargetFile.isDropBoxFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);

            if (mSourceFile.isDropBoxFile()) {
                // we're in the same provider, use api method
                cloudStorageDropbox.copy(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                return;
            }
        } else if (mTargetFile.isBoxFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);

            if (mSourceFile.isBoxFile()) {
                // we're in the same provider, use api method
                cloudStorageBox.copy(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else if (mTargetFile.isGoogleDriveFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);

            if (mSourceFile.isGoogleDriveFile()) {
                // we're in the same provider, use api method
                cloudStorageGdrive.copy(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else if (mTargetFile.isOneDriveFile()) {
            // API doesn't support output stream, we'll upload the file directly
            CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE);

            if (mSourceFile.isOneDriveFile()) {
                // we're in the same provider, use api method
                cloudStorageOnedrive.copy(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath()),
                        CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()));
                return;
            } else {
                cloudStorageOnedrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()),
                        bufferedInputStream, mSourceFile.getSize(), true);
                bufferedInputStream.close();
                return;
            }
        } else {
            // copying normal file, target not in OTG
            File file = new File(mTargetFile.getPath());
            if (FileUtil.isWritable(file)) {

                if (lowOnMemory) {
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
                } else {

                    outChannel = new RandomAccessFile(file, "rw").getChannel();
                }
            } else {
                ContentResolver contentResolver = mContext.getContentResolver();
                DocumentFile documentTargetFile = FileUtil.getDocumentFile(file, mTargetFile.isDirectory(),
                        mContext);

                bufferedOutputStream = new BufferedOutputStream(
                        contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE);
            }
        }

        if (bufferedInputStream != null) {
            if (bufferedOutputStream != null)
                copyFile(bufferedInputStream, bufferedOutputStream);
            else if (outChannel != null) {
                copyFile(bufferedInputStream, outChannel);
            }
        } else if (inChannel != null) {
            if (bufferedOutputStream != null)
                copyFile(inChannel, bufferedOutputStream);
            else if (outChannel != null)
                copyFile(inChannel, outChannel);
        }

    } catch (IOException e) {
        e.printStackTrace();
        Log.d(getClass().getSimpleName(), "I/O Error!");
        throw new IOException();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();

        // we ran out of memory to map the whole channel, let's switch to streams
        AppConfig.toast(mContext, mContext.getString(R.string.copy_low_memory));

        startCopy(true);
    } finally {

        try {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
            if (bufferedInputStream != null)
                bufferedInputStream.close();
            if (bufferedOutputStream != null)
                bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            // failure in closing stream
        }

        //If target file is copied onto the device and copy was successful, trigger media store
        //rescan

        if ((mTargetFile.isLocal() || mTargetFile.isOtgFile()) && mTargetFile.exists(mContext)) {

            DocumentFile documentFile = FileUtil.getDocumentFile(mTargetFile.getFile(), false, mContext);
            //If FileUtil.getDocumentFile() returns null, fall back to DocumentFile.fromFile()
            if (documentFile == null)
                documentFile = DocumentFile.fromFile(mTargetFile.getFile());

            FileUtils.scanFile(documentFile.getUri(), mContext);
        }
    }
}

From source file:com.nextgis.ngm_clink_monitoring.fragments.CreateObjectFragment.java

protected void writePhotoAttach(File tempPhotoFile) throws IOException {
    GISApplication app = (GISApplication) getActivity().getApplication();

    ContentResolver contentResolver = app.getContentResolver();
    String photoFileName = getPhotoFileName(tempPhotoFile);
    Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), photoFileName: " + photoFileName);

    Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName
            + "/" + mObjectId + "/attach");
    Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), allAttachesUri: " + allAttachesUri);

    ContentValues values = new ContentValues();
    values.put(VectorLayer.ATTACH_DISPLAY_NAME, photoFileName);
    values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg");
    //values.put(VectorLayer.ATTACH_DESCRIPTION, photoFileName);

    Uri attachUri = null;//from w w  w  . ja v a  2s . c o  m
    String insertAttachError = null;
    try {
        attachUri = contentResolver.insert(allAttachesUri, values);
        Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), insert: " + attachUri.toString());
    } catch (Exception e) {
        Log.d(TAG,
                "CreateObjectFragment, writePhotoAttach(), Insert attach failed: " + e.getLocalizedMessage());
        insertAttachError = "Insert attach failed: " + e.getLocalizedMessage();
    }

    if (null != attachUri) {
        int exifOrientation = BitmapUtil.getOrientationFromExif(tempPhotoFile);

        // resize and rotate
        Bitmap sourceBitmap = BitmapFactory.decodeFile(tempPhotoFile.getPath());
        Bitmap resizedBitmap = BitmapUtil.getResizedBitmap(sourceBitmap, FoclConstants.PHOTO_MAX_SIZE_PX,
                FoclConstants.PHOTO_MAX_SIZE_PX);
        Bitmap rotatedBitmap = BitmapUtil.rotateBitmap(resizedBitmap, exifOrientation);

        // jpeg compress
        File tempAttachFile = File.createTempFile("attach", null, app.getCacheDir());
        OutputStream tempOutStream = new FileOutputStream(tempAttachFile);
        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, FoclConstants.PHOTO_JPEG_COMPRESS_QUALITY,
                tempOutStream);
        tempOutStream.close();

        int newHeight = rotatedBitmap.getHeight();
        int newWidth = rotatedBitmap.getWidth();

        rotatedBitmap.recycle();

        // write EXIF to new file
        BitmapUtil.copyExifData(tempPhotoFile, tempAttachFile);
        BitmapUtil.writeLocationToExif(tempAttachFile, mAccurateLocation, app.getGpsTimeOffset());

        ExifInterface attachExif = new ExifInterface(tempAttachFile.getCanonicalPath());

        attachExif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL);
        attachExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, "" + newHeight);
        attachExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, "" + newWidth);

        attachExif.saveAttributes();

        // attach data from tempAttachFile
        OutputStream attachOutStream = contentResolver.openOutputStream(attachUri);
        if (attachOutStream != null) {
            FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream);
            attachOutStream.close();
        } else {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), attachOutStream == null, attachUri"
                    + attachUri.toString());
        }

        if (!tempAttachFile.delete()) {
            Log.d(TAG,
                    "CreateObjectFragment, writePhotoAttach(), tempAttachFile.delete() failed, tempAttachFile:"
                            + tempAttachFile.getAbsolutePath());
        }
    }

    if (app.isOriginalPhotoSaving()) {
        BitmapUtil.writeLocationToExif(tempPhotoFile, mAccurateLocation, app.getGpsTimeOffset());
        File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName);

        if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), move original failed, tempPhotoFile:"
                    + tempPhotoFile.getAbsolutePath() + ", origPhotoFile: " + origPhotoFile.getAbsolutePath());
            throw new IOException(
                    "Save original photo failed, tempPhotoFile: " + tempPhotoFile.getAbsolutePath());
        }

    } else {
        if (!tempPhotoFile.delete()) {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), tempPhotoFile.delete() failed, tempPhotoFile:"
                    + tempPhotoFile.getAbsolutePath());
        }
    }

    if (null != insertAttachError) {
        throw new IOException(insertAttachError);
    }
}