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

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현