So after 3 days of wanting to jump off a cliff. I found the answer. Of course it was a few minutes after asking the question here (first question ever so be kind.). The only Issue is you need a SSL cert for HTTPS on the server retrieving the file. My server is http but i can get a cert in there and fix that. to Test i threw up a github repository and linked to the raw text file. Here is my solution if this saves you 3 days pour one out for me.

Thread {
            try {
                val url = URL("https://raw.githubusercontent.com/USERNAME/NeedHTTPSdontWanaSSL/main/info.txt")
                val uc: HttpsURLConnection = url.openConnection() as HttpsURLConnection
                val br = BufferedReader(InputStreamReader(uc.getInputStream()))
                var line: String?
                val lin2 = StringBuilder()
                while (br.readLine().also { line = it } != null) {
                    lin2.append(line)
                }
                Log.d("The Text", "$lin2")
            } catch (e: IOException) {
                Log.d("texts", "onClick: " + e.getLocalizedMessage())
                e.printStackTrace()
            }
        }.start()

Credit: answered Aug 12, 2018 at 9:29 Aishik kirtaniya Android - How can I read a text file from a url?

Answer from GraduatedImposterSynd on Stack Overflow
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › reading from a file in kotlin
Reading from a File in Kotlin | Baeldung on Kotlin
April 28, 2026 - In this quick tutorial, we’ll learn about the various ways of reading a file in Kotlin. We’ll cover both use cases of reading the entire file as a String, as well as reading it into a list of individual lines. Also obtaining it from a full absolute path or from a project resource.
Top answer
1 of 2
3

So after 3 days of wanting to jump off a cliff. I found the answer. Of course it was a few minutes after asking the question here (first question ever so be kind.). The only Issue is you need a SSL cert for HTTPS on the server retrieving the file. My server is http but i can get a cert in there and fix that. to Test i threw up a github repository and linked to the raw text file. Here is my solution if this saves you 3 days pour one out for me.

Thread {
            try {
                val url = URL("https://raw.githubusercontent.com/USERNAME/NeedHTTPSdontWanaSSL/main/info.txt")
                val uc: HttpsURLConnection = url.openConnection() as HttpsURLConnection
                val br = BufferedReader(InputStreamReader(uc.getInputStream()))
                var line: String?
                val lin2 = StringBuilder()
                while (br.readLine().also { line = it } != null) {
                    lin2.append(line)
                }
                Log.d("The Text", "$lin2")
            } catch (e: IOException) {
                Log.d("texts", "onClick: " + e.getLocalizedMessage())
                e.printStackTrace()
            }
        }.start()

Credit: answered Aug 12, 2018 at 9:29 Aishik kirtaniya Android - How can I read a text file from a url?

2 of 2
0

How about this?

import java.net.URL

val s = "https://www.someplace.com/dir/file.txt"
val text = URL(s).openStream().readAllBytes().decodeToString()

Wrap it in some exception handling if you want. So long as you don't keep references to the intermediate stream, it'll immediately be eligible for garbage collection. The stream will be closed when it's garbage collected, thus I don't bother with adding a call to explicitly close it.

Discussions

Can I convert url to File?
While you don't need a File instance, can pass the String directly, it probably won't work as you expect. That's not really about Kotlin but the Telegram API. The send video method is for sending files, either local or providing a URL where Telegram can download the file. It is not valid for YouTube or other media streaming services since the URL is not a file for downloading but a link to the player. https://core.telegram.org/bots/api#sendvideo I guess you can send a plain text message with the YouTube video HTTPS URL, although I don't know if the Telegram client will embed the YouTube player or not. Maybe there's another method for embedded content. Apparently there's an inline mode to embed content, maybe that's what you need for YouTube videos, not really sure since I've never used Telegram... but there's an API for embedding videos like YouTube in that mode. Edit: Refactored and clarified More on reddit.com
🌐 r/Kotlin
4
2
March 7, 2022
java - Android - How can I read a text file from a url? - Stack Overflow
To subscribe to this RSS feed, copy and paste this URL into your RSS reader. More on stackoverflow.com
🌐 stackoverflow.com
How to read a text file from resources in Kotlin? - Stack Overflow
I want to write a Spek test in Kotlin. How to read an HTML file from the src/test/resources folder? More on stackoverflow.com
🌐 stackoverflow.com
Load image file in Kotlin
Canvas::class.java.getResourceAsStream("fieldDiagram.png") More on reddit.com
🌐 r/Kotlin
5
1
January 27, 2018
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.net.-u-r-l › read-text.html
readText - Kotlin Programming Language
January 14, 2022 - Try the revamped Kotlin docs design! ... Reads the entire content of this URL as a String using UTF-8 or the specified charset. This method is not recommended on huge files.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › read-text.html
readText | Core API – Kotlin Programming Language
This method is not recommended on huge files. It has an internal limitation of 2 GB file size. ... Reads this reader completely as a String. Note: It is the caller's responsibility to close this reader. ... Reads the entire content of this URL as a String using UTF-8 or the specified charset.
🌐
Android Developers
developer.android.com › api reference › url
URL | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
en.proft.me
en.proft.me › 2018 › 04 › 19 › how-fetch-data-over-network-kotlin-and-android
How to fetch data over network in Kotlin and Android | en.proft.me
April 19, 2018 - Making a network request in Kotlin is straightforward with simple syntax. Here's how you would read data over the internet in Kotlin: val response = URL("https://httpbin.org/get").readText()
🌐
A2zapk
a2zapk.co › home › how to read a text file from a url in kotlin (android studio guide)
How to Read a Text File from a URL in Kotlin (Android Studio Guide) - a2zapk.co
May 26, 2025 - -> Unit) { CoroutineScope(Dispatchers.IO).launch { try { val url = URL(urlString) val connection = url.openConnection() as HttpURLConnection connection.connectTimeout = 5000 connection.readTimeout = 5000 val inputStream = connection.inputStream val reader = BufferedReader(InputStreamReader(inputStream)) val content = reader.readText() withContext(Dispatchers.Main) { onResult(content) } reader.close() connection.disconnect() } catch (e: Exception) { withContext(Dispatchers.Main) { onResult(null) } } } } val fileUrl = "https://example.com/data.txt" readTextFileFromUrl(fileUrl) { content -> if (content != null) { Log.d("FileContent", content) } else { Log.e("FileError", "Failed to load content") } }
Find elsewhere
🌐
W3cubDocs
docs.w3cub.com › kotlin › api › latest › jvm › stdlib › kotlin.io › java.net.-u-r-l › read-text
kotlin.io.java.net.URL.readText - Kotlin - W3cubDocs
Reads the entire content of this URL as a String using UTF-8 or the specified charset. This method is not recommended on huge files. ... Return a string with this URL entire content. © 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors Licensed under the Apache License, ...
🌐
DEV Community
dev.to › arkilis › download-image-from-url-in-kotlin-4fc6
Download image from URL in Kotlin - DEV Community
February 20, 2023 - Here's an example of how to use the URL and readBytes to download an image from a URL in Kotlin: import java.net.URL import kotlin.io.readBytes fun main() { val url = URL("https://www.example.com/image.png") val imageData = url.readBytes() // TODO: ...
🌐
GitHub
gist.github.com › ff65086bc60e606ef6a00f86ef6316c6
Read data from URL in Kotlin. · GitHub
Read data from URL in Kotlin. ... This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Steemit
steemit.com › kotlin › @phash › java-vs-kotlin-read-json-from-url
Java vs Kotlin - read JSON from URL — Steemit
September 3, 2018 - what a bunch of code.. just to retrieve a single JSON File from a distant server ... can't there be an easier way? We are in 2018, not in 1994... damn... OH wait! fun getJsonFromURL(wantedURL: String) : String { return URL(wantedURL).readText() } ok... ffs you should surround this by some try/catch for the malformed URL and / or IOExceptions etc... but at the end, it is a little bit shorter, isn't it? What do you think of Kotlin?
Top answer
1 of 4
17

Try using an HTTPUrlConnection or a OKHTTP Request to get the info, here try this:

Always do any kind of networking in a background thread else android will throw a NetworkOnMainThread Exception

new Thread(new Runnable(){

  public void run(){


    ArrayList<String> urls=new ArrayList<String>(); //to read each line
    //TextView t; //to show the result, please declare and find it inside onCreate()



    try {
         // Create a URL for the desired page
         URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location
         //First open the connection 
         HttpURLConnection conn=(HttpURLConnection) url.openConnection();
         conn.setConnectTimeout(60000); // timing out in a minute

         BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

         //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
        String str;
        while ((str = in.readLine()) != null) {
            urls.add(str);
        }
        in.close();
    } catch (Exception e) {
        Log.d("MyTag",e.toString());
    } 

    //since we are in background thread, to post results we have to go back to ui thread. do the following for that

    Activity.this.runOnUiThread(new Runnable(){
      public void run(){
          t.setText(urls.get(0)); // My TextFile has 3 lines
      }
    });

  }
}).start();
2 of 4
6

1-) Add internet permission to your Manifest file.

2-) Make sure that you are launching your code in separate thread.

Here is the snippet which works for me great.

    public List<String> getTextFromWeb(String urlString)
    {
        URLConnection feedUrl;
        List<String> placeAddress = new ArrayList<>();

        try
        {
            feedUrl = new URL(urlString).openConnection();
            InputStream is = feedUrl.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));          
            String line = null;

            while ((line = reader.readLine()) != null) // read line by line
            {
                placeAddress.add(line); // add line to list
            }
            is.close(); // close input stream

            return placeAddress; // return whatever you need
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }

Our reader function is ready, let's call it by using another thread

            new Thread(new Runnable()
            {
                public void run()
                {
                    final List<String> addressList = getTextFromWeb("http://www.google.com/sometext.txt"); // format your URL
                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            //update ui
                        }
                    });
                }
            }).start();
🌐
BezKoder
bezkoder.com › home › how to read file in kotlin
How to read File in Kotlin - BezKoder
February 16, 2020 - In this tutorial, I will show you how to read File in Kotlin using InputStream or BufferedReader or File directly.
🌐
Atomic Spin
spin.atomicobject.com › 2020 › 05 › 18 › android-download-files-kotlin
Download Files in Kotlin for Android Using Ktor and Intents
June 18, 2025 - Downloading the file opens the output stream to the URI given and dispatches the download file coroutine. The download itself is handled on the IO thread, but the emitter results are handled on the Main thread.
🌐
Medium
medium.com › mobile-app-development-publication › download-file-in-android-with-kotlin-874d50bccaa2
Download File in Android with Kotlin | by Elye - A Dev By Grace | Mobile App Development Publication | Medium
September 5, 2020 - Learning Android Development Download File in Android with Kotlin Download with feedback of progress in Kotlin Sometimes we need to download files in our Android App, e.g. to display a PDF file. The …
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.net.-u-r-l › read-bytes.html
readBytes - Kotlin Programming Language
Try the revamped Kotlin docs design! ... Reads the entire content of the URL as byte array. This method is not recommended on huge files.
🌐
GeeksforGeeks
geeksforgeeks.org › kotlin › load-pdf-from-url-in-android-with-kotlin
Load PDF From URL in Android with Kotlin - GeeksforGeeks
July 23, 2025 - Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. ... package com.gtappdevelopers.kotlingfgproject import android.os.AsyncTask import android.os.Build import android.os.Bundle import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import com.github.barteksc.pdfviewer.PDFView import java.io.BufferedInputStream import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import javax.net.ssl.HttpsURLConnection class MainActivity : AppCompatActivity() { // on below line we are creating // a variable for our pdf view.