Saving file in internal storage using Uri (obtained from Storage Access network)How do I obtain crash-data from my Android application?Convert file: Uri to File in AndroidGet filename and path from URI from mediastoreIs there a way to get the source code from an APK file?Getting data from the server and loading new screen using AndroidTaking Picture via intent to internal (app) storage returns null for bitmapandroid.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()Saving an image after getting folder from Storage Access Framework UIError json parsingApp crash when use mobie data (3g/4g)

What food production methods would allow a metropolis like New York to become self sufficient

Why was this sacrifice sufficient?

Is the homebrew weapon attack cantrip 'Arcane Strike' balanced?

Drawing Quarter-Circle

Why does the Earth follow an elliptical trajectory rather than a parabolic one?

How to pronounce "r" after a "g"?

Why can't RGB or bicolour LEDs produce a decent yellow?

Ex-manager wants to stay in touch, I don't want to

Delta TSA-Precheck status removed

How do I tell my supervisor that he is choosing poor replacements for me while I am on maternity leave?

The lexical root of the perfect tense forms differs from the lexical root of the infinitive form

Why does a C.D.F need to be right-continuous?

Understanding basic photoresistor circuit

How to make a language evolve quickly?

Looking for a simple way to manipulate one column of a matrix

How old is Captain America at the end of "Avengers: Endgame"?

Increase height of laser cut design file for enclosure

On studying Computer Science vs. Software Engineering to become a proficient coder

Was there a contingency plan in place if Little Boy failed to detonate?

Is the schwa sound consistent?

semanage not changing file context

Why in a Ethernet LAN, a packet sniffer can obtain all packets sent over the LAN?

Early arrival in Australia, early hotel check in not available

Guns in space with bullets that return?



Saving file in internal storage using Uri (obtained from Storage Access network)


How do I obtain crash-data from my Android application?Convert file: Uri to File in AndroidGet filename and path from URI from mediastoreIs there a way to get the source code from an APK file?Getting data from the server and loading new screen using AndroidTaking Picture via intent to internal (app) storage returns null for bitmapandroid.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()Saving an image after getting folder from Storage Access Framework UIError json parsingApp crash when use mobie data (3g/4g)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm using Storage Access Network to pick file and save in internal storage so that app can use if in future.



I'm getting URI without any issues. It's something like content://com.android.providers.media.documents/document/image%3A141274



Problem comes when I'm trying to save image into internal directory. Code passes without crashes, image with same size is saved into internal directory (I can see it in device Explorer: https://take.ms/3TwBS).
But image itself is broken and can't be opened.



Here's code I'm using (after getting URI)



val destinationFile = File("$context.filesDir.absolutePath/$fileName")
try
val writer = FileWriter(destinationFile)
writer.append(readTextFromUri(it))
writer.flush()
writer.close()

catch (e: Exception)
e.printStackTrace()




@Throws(IOException::class)
private fun readTextFromUri(uri: Uri): String
val inputStream = activity!!.contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val stringBuilder = StringBuilder()
var line: String? = null
while ( line = reader.readLine(); line () != null)
stringBuilder.append(line)

inputStream?.close()
reader.close()
return stringBuilder.toString()










share|improve this question






















  • Your code is for reading and writing text. Your question implies that you are reading and writing images. Images are not text.

    – CommonsWare
    Mar 23 at 11:26











  • Correct, I already got to the point that content is broken during copying. So the right question is how to properly copy to File using InputStream.

    – Александр Бабич
    Mar 23 at 12:24






  • 1





    Use the copyTo() extension function to copy the contents of an InputStream to an OutputStream: kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/…

    – CommonsWare
    Mar 23 at 12:30

















1















I'm using Storage Access Network to pick file and save in internal storage so that app can use if in future.



I'm getting URI without any issues. It's something like content://com.android.providers.media.documents/document/image%3A141274



Problem comes when I'm trying to save image into internal directory. Code passes without crashes, image with same size is saved into internal directory (I can see it in device Explorer: https://take.ms/3TwBS).
But image itself is broken and can't be opened.



Here's code I'm using (after getting URI)



val destinationFile = File("$context.filesDir.absolutePath/$fileName")
try
val writer = FileWriter(destinationFile)
writer.append(readTextFromUri(it))
writer.flush()
writer.close()

catch (e: Exception)
e.printStackTrace()




@Throws(IOException::class)
private fun readTextFromUri(uri: Uri): String
val inputStream = activity!!.contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val stringBuilder = StringBuilder()
var line: String? = null
while ( line = reader.readLine(); line () != null)
stringBuilder.append(line)

inputStream?.close()
reader.close()
return stringBuilder.toString()










share|improve this question






















  • Your code is for reading and writing text. Your question implies that you are reading and writing images. Images are not text.

    – CommonsWare
    Mar 23 at 11:26











  • Correct, I already got to the point that content is broken during copying. So the right question is how to properly copy to File using InputStream.

    – Александр Бабич
    Mar 23 at 12:24






  • 1





    Use the copyTo() extension function to copy the contents of an InputStream to an OutputStream: kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/…

    – CommonsWare
    Mar 23 at 12:30













1












1








1


1






I'm using Storage Access Network to pick file and save in internal storage so that app can use if in future.



I'm getting URI without any issues. It's something like content://com.android.providers.media.documents/document/image%3A141274



Problem comes when I'm trying to save image into internal directory. Code passes without crashes, image with same size is saved into internal directory (I can see it in device Explorer: https://take.ms/3TwBS).
But image itself is broken and can't be opened.



Here's code I'm using (after getting URI)



val destinationFile = File("$context.filesDir.absolutePath/$fileName")
try
val writer = FileWriter(destinationFile)
writer.append(readTextFromUri(it))
writer.flush()
writer.close()

catch (e: Exception)
e.printStackTrace()




@Throws(IOException::class)
private fun readTextFromUri(uri: Uri): String
val inputStream = activity!!.contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val stringBuilder = StringBuilder()
var line: String? = null
while ( line = reader.readLine(); line () != null)
stringBuilder.append(line)

inputStream?.close()
reader.close()
return stringBuilder.toString()










share|improve this question














I'm using Storage Access Network to pick file and save in internal storage so that app can use if in future.



I'm getting URI without any issues. It's something like content://com.android.providers.media.documents/document/image%3A141274



Problem comes when I'm trying to save image into internal directory. Code passes without crashes, image with same size is saved into internal directory (I can see it in device Explorer: https://take.ms/3TwBS).
But image itself is broken and can't be opened.



Here's code I'm using (after getting URI)



val destinationFile = File("$context.filesDir.absolutePath/$fileName")
try
val writer = FileWriter(destinationFile)
writer.append(readTextFromUri(it))
writer.flush()
writer.close()

catch (e: Exception)
e.printStackTrace()




@Throws(IOException::class)
private fun readTextFromUri(uri: Uri): String
val inputStream = activity!!.contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val stringBuilder = StringBuilder()
var line: String? = null
while ( line = reader.readLine(); line () != null)
stringBuilder.append(line)

inputStream?.close()
reader.close()
return stringBuilder.toString()







android kotlin storage-access-framework






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 10:54









Александр БабичАлександр Бабич

145111




145111












  • Your code is for reading and writing text. Your question implies that you are reading and writing images. Images are not text.

    – CommonsWare
    Mar 23 at 11:26











  • Correct, I already got to the point that content is broken during copying. So the right question is how to properly copy to File using InputStream.

    – Александр Бабич
    Mar 23 at 12:24






  • 1





    Use the copyTo() extension function to copy the contents of an InputStream to an OutputStream: kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/…

    – CommonsWare
    Mar 23 at 12:30

















  • Your code is for reading and writing text. Your question implies that you are reading and writing images. Images are not text.

    – CommonsWare
    Mar 23 at 11:26











  • Correct, I already got to the point that content is broken during copying. So the right question is how to properly copy to File using InputStream.

    – Александр Бабич
    Mar 23 at 12:24






  • 1





    Use the copyTo() extension function to copy the contents of an InputStream to an OutputStream: kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/…

    – CommonsWare
    Mar 23 at 12:30
















Your code is for reading and writing text. Your question implies that you are reading and writing images. Images are not text.

– CommonsWare
Mar 23 at 11:26





Your code is for reading and writing text. Your question implies that you are reading and writing images. Images are not text.

– CommonsWare
Mar 23 at 11:26













Correct, I already got to the point that content is broken during copying. So the right question is how to properly copy to File using InputStream.

– Александр Бабич
Mar 23 at 12:24





Correct, I already got to the point that content is broken during copying. So the right question is how to properly copy to File using InputStream.

– Александр Бабич
Mar 23 at 12:24




1




1





Use the copyTo() extension function to copy the contents of an InputStream to an OutputStream: kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/…

– CommonsWare
Mar 23 at 12:30





Use the copyTo() extension function to copy the contents of an InputStream to an OutputStream: kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/…

– CommonsWare
Mar 23 at 12:30












1 Answer
1






active

oldest

votes


















0














As @CommonsWare described I should have used proper dealing with files, not texts.



Proper way to do:



private fun inputStreamToFile(uri: Uri)
val inputStream = contentResolver.openInputStream(uri)
val output = FileOutputStream(File("$filesDir.absoluteFile/magic.png"))
inputStream?.copyTo(output, 4 * 1024)



Or longer way (without extension functions)



fun inputStreamToFile(uri: Uri)
val inputStream = contentResolver.openInputStream(uri)
inputStream.use
val directory = getDir("test", Context.MODE_PRIVATE)
val file = File(directory, "correct.txt")
val output = FileOutputStream(file)
output.use
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int = inputStream?.read(buffer) ?: -1
while (read != -1)
output.write(buffer, 0, read)
read = inputStream?.read(buffer) ?: -1

output.flush()








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55312954%2fsaving-file-in-internal-storage-using-uri-obtained-from-storage-access-network%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    As @CommonsWare described I should have used proper dealing with files, not texts.



    Proper way to do:



    private fun inputStreamToFile(uri: Uri)
    val inputStream = contentResolver.openInputStream(uri)
    val output = FileOutputStream(File("$filesDir.absoluteFile/magic.png"))
    inputStream?.copyTo(output, 4 * 1024)



    Or longer way (without extension functions)



    fun inputStreamToFile(uri: Uri)
    val inputStream = contentResolver.openInputStream(uri)
    inputStream.use
    val directory = getDir("test", Context.MODE_PRIVATE)
    val file = File(directory, "correct.txt")
    val output = FileOutputStream(file)
    output.use
    val buffer = ByteArray(4 * 1024) // or other buffer size
    var read: Int = inputStream?.read(buffer) ?: -1
    while (read != -1)
    output.write(buffer, 0, read)
    read = inputStream?.read(buffer) ?: -1

    output.flush()








    share|improve this answer



























      0














      As @CommonsWare described I should have used proper dealing with files, not texts.



      Proper way to do:



      private fun inputStreamToFile(uri: Uri)
      val inputStream = contentResolver.openInputStream(uri)
      val output = FileOutputStream(File("$filesDir.absoluteFile/magic.png"))
      inputStream?.copyTo(output, 4 * 1024)



      Or longer way (without extension functions)



      fun inputStreamToFile(uri: Uri)
      val inputStream = contentResolver.openInputStream(uri)
      inputStream.use
      val directory = getDir("test", Context.MODE_PRIVATE)
      val file = File(directory, "correct.txt")
      val output = FileOutputStream(file)
      output.use
      val buffer = ByteArray(4 * 1024) // or other buffer size
      var read: Int = inputStream?.read(buffer) ?: -1
      while (read != -1)
      output.write(buffer, 0, read)
      read = inputStream?.read(buffer) ?: -1

      output.flush()








      share|improve this answer

























        0












        0








        0







        As @CommonsWare described I should have used proper dealing with files, not texts.



        Proper way to do:



        private fun inputStreamToFile(uri: Uri)
        val inputStream = contentResolver.openInputStream(uri)
        val output = FileOutputStream(File("$filesDir.absoluteFile/magic.png"))
        inputStream?.copyTo(output, 4 * 1024)



        Or longer way (without extension functions)



        fun inputStreamToFile(uri: Uri)
        val inputStream = contentResolver.openInputStream(uri)
        inputStream.use
        val directory = getDir("test", Context.MODE_PRIVATE)
        val file = File(directory, "correct.txt")
        val output = FileOutputStream(file)
        output.use
        val buffer = ByteArray(4 * 1024) // or other buffer size
        var read: Int = inputStream?.read(buffer) ?: -1
        while (read != -1)
        output.write(buffer, 0, read)
        read = inputStream?.read(buffer) ?: -1

        output.flush()








        share|improve this answer













        As @CommonsWare described I should have used proper dealing with files, not texts.



        Proper way to do:



        private fun inputStreamToFile(uri: Uri)
        val inputStream = contentResolver.openInputStream(uri)
        val output = FileOutputStream(File("$filesDir.absoluteFile/magic.png"))
        inputStream?.copyTo(output, 4 * 1024)



        Or longer way (without extension functions)



        fun inputStreamToFile(uri: Uri)
        val inputStream = contentResolver.openInputStream(uri)
        inputStream.use
        val directory = getDir("test", Context.MODE_PRIVATE)
        val file = File(directory, "correct.txt")
        val output = FileOutputStream(file)
        output.use
        val buffer = ByteArray(4 * 1024) // or other buffer size
        var read: Int = inputStream?.read(buffer) ?: -1
        while (read != -1)
        output.write(buffer, 0, read)
        read = inputStream?.read(buffer) ?: -1

        output.flush()









        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 23 at 12:38









        Александр БабичАлександр Бабич

        145111




        145111





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55312954%2fsaving-file-in-internal-storage-using-uri-obtained-from-storage-access-network%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript