Android Week: Reading from a bundled file

Since last week we had a look at iOS, this week we’ll be looking at something to do with Android every day. Today, a Kotlin function that not many people might know about.

Kotlin provides us with some great language features to make our lives easier, and today we’ll be talking about one – use. Use is an inline function from the Kotlin standard library which will use a resource, such as a buffered reader, and then close the resource when finished. The great thing with use is that even if an exception occurs while reading the file, the input is still closed. This means we don’t have to worry about managing this ourselves.

Let’s take a look. We’ll start by bundling a text file in an assets directory. Swap your view of your project from Android to Project so you can see the main directory. Right click main and add a new directory and call it assets. Now right click this and add a new text file. Write whatever you want in that text file.

Now back wherever you want to use this, add the following bit of code:

Screen Shot 2018-03-30 at 20.29.55

This will open the file, create a buffered reader, use it to read the text, close it once finished, and then assign the contents to a variable. And that’s it! We can now print that variable and see the contents of our text file. We haven’t had to worry about closing the bufferedReader afterwards and we can assign it to a variable right there in line.

The same thing can be applied to a File instance, if you want to read that, rather than creating a buffered reader and reading and then closing yourself, try the use function instead!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s