Bytearray to file kotlin

I/O With Kotlin

To get ready to show for loops, if expressions, and other Kotlin constructs, let’s take a look at how to handle I/O with Kotlin.

Writing to STDOUT and STDERR

Write to standard out (STDOUT) using println :

println("Hello, world") // includes newline print("Hello without newline") // no newline character 

Because println is so commonly used, there’s no need to import it.

System.err.println("yikes, an error happened") 

Reading command-line input

A simple way to read command-line (console) input is with the readLine() function:

print("Enter your name: ") val name = readLine() 

readLine() provides a simple way to read input. For more complicated needs you can also use the java.util.Scanner class, as shown in this example:

import java.util.Scanner val scanner = Scanner(System.`in`) print("Enter an int: ") val i: Int = scanner.nextInt() println("i = $i") 

Just be careful with the Scanner class. If you’re looking for an Int and the user enters something else, you’ll end up with a InputMismatchException :

>>> val i: Int = scanner.nextInt() 1.1 java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) 

Reading text files

There are a number of ways to read text files in Kotlin. While this approach isn’t recommended for large text files, it’s a simple way to read small-ish text files into a List :

import java.io.File fun readFile(filename: String): List = File(filename).readLines() 

Here’s how you use that function to read the /etc/passwd file:

val lines = readFile("/etc/passwd") 

And here are two ways to print all of those lines to STDOUT:

lines.forEach < println(it) >lines.forEach < line ->println(line) > 

Other ways to read text files

Here are a few other ways to read text files in Kotlin:

fun readFile(filename: String): List = File(filename).readLines() fun readFile(filename: String): List = File(filename).bufferedReader().readLines() fun readFile(filename: String): List = File(filename).useLines < it.toList() >fun readFile(filename: String): String = File(filename).inputStream().readBytes().toString(Charsets.UTF_8) val text = File("/etc/passwd").bufferedReader().use

The file-reading function signatures look like this:

// Do not use this function for huge files. fun File.readLines( charset: Charset = Charsets.UTF_8 ): List fun File.bufferedReader( charset: Charset = Charsets.UTF_8, bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedReader fun File.reader( charset: Charset = Charsets.UTF_8 ): InputStreamReader fun File.useLines( charset: Charset = Charsets.UTF_8, block: (Sequence) -> T ): T // This method is not recommended on huge files. It has an internal limitation of 2 GB byte array size. fun File.readBytes(): ByteArray // This method is not recommended on huge files. It has an internal limitation of 2 GB file size. fun File.readText(charset: Charset = Charsets.UTF_8): String 

See the Kotlin java.io.File documentation for more information and caveats about the methods shown ( readLines , useLines , etc.).

Читайте также:  Php имя функции внутри функции

Writing text files

There are several ways to write text files in Kotlin. Here’s a simple approach:

File(filename).writeText(string) 

That approach default to the UTF-8 character set. You can also specify the Charset when using writeText :

File(filename).writeText(string, Charset.forName("UTF-16")) 

Other ways to write files

There are other ways to write to files in Kotlin. Here are some examples:

File(filename).writeBytes(byteArray) File(filename).printWriter().use < out ->out.println(string) > File(filename).bufferedWriter().use < out ->out.write(string) > 

The file-writing function signatures look like this:

fun File.writeText( text: String, charset: Charset = Charsets.UTF_8 ) fun File.writeBytes(array: ByteArray) fun File.printWriter( charset: Charset = Charsets.UTF_8 ): PrintWriter fun File.bufferedWriter( charset: Charset = Charsets.UTF_8, bufferSize: Int = DEFAULT_BUFFER_SIZE ): BufferedWriter 

See the Kotlin java.io.File documentation for more information about the methods shown.

Источник

Different ways to write to a file in Kotlin

Kotlin provides different ways to write to a file as direct methods and as extension methods. In this post, I will show you examples of different methods on how to write content to a file.

Method 1: By using File.writeText and File.appendText:

File.writeText is defined in java.io.File and using this method we can directly write one string to a file. Below is the definition of this method:

fun File.writeText( str: String, char: Charset = Charsets.UTF_8)

Here, str is the string that we are writing to the file and char is the Charset we are using. This is an optional value and by default it takes UTF-8.

package com.company import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/sample.txt" val givenStr = "Hello World !!" val file = File(filePath) file.writeText(givenStr) >
  • filePath is the path of the file. Change it to your own file path
  • givenStr is the string we are writing to the file.
  • We created one File object with the file path and used writeText to write givenStr in that file.

It will write the below content to the file:

Note that it replaces the content in the file. appendText is another method that can be used to append to the existing content of a file.

package com.company import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/sample.txt" val givenStr = "Hello World !!" val file = File(filePath) file.writeText(givenStr) file.appendText(givenStr) >

The file will hold the below content:

Method 2: By using File.writeBytes():

writeBytes is another method that can be used to write an array of bytes to a file. This method is defined as below:

fun File.writeBytes(array: ByteArray)

It takes a ByteArray and writes that byte array to the file.

Below program shows how we can use this method:

package com.company import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/sample.txt" val givenStr = "Hello World !!" val file = File(filePath) file.writeBytes(givenStr.toByteArray()) >
  • we are converting the string givenStr to a byte array using toByteArray() method and writing that in the file using writeBytes

It will add the below line to the file:

It is not appending the content to the file. For that, we need to use appendBytes method.

Method 3: By using PrintWriter:

java.io.File PrintWriter can be used by printWriter() method provided in Kotlin. This method returns one PrintWriter instance. We can use use<> to handle it.

package com.company import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/sample.txt" File(filePath).printWriter().use file -> file.print('H') file.print("ello") file.println() file.println("World") > >

It will print the below lines to the file:

Method 4: By using BufferedWriter:

Kotlin profiles another method called bufferedWriter that returns a new BufferedWriter object. We can use use<> on it to write different contents to a file.

package com.company import java.io.File fun main()  val filePath = "/Users/cvc/IdeaProjects/KotlinSampleProgram/src/sample.txt" File(filePath).bufferedWriter().use file -> file.write("Hello ") file.write("World") > >

It will print the below content to the file:

Источник

How to write to a file in Kotlin

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Overview

There are multiple ways to write to a file in Kotlin. We’ll discuss the following two ways:

The writeText() method

It’s easier to write to a file using the writeText() method. It allows us to write a string to a file. The method first encodes the given text to the specified encoding and then internally uses the writeBytes() method to write to a file.

Syntax

File.writeText(text: String, charset: Charset = Charsets.UTF_8) 

Parameter

  • text : We use this parameter text/string to write to a file.
  • charset : We use this character set/encoding.

Code

import java.io.File
fun main()
val fileName = "file.txt"
val myFile = File(fileName)
val content = "Educative is the best platform."
myFile.writeText(content)
println("Written to the file")
>

The writeBytes() method

The writeBytes() method writes a ByteArray to the specified file.

Syntax

File.writeBytes(array: ByteArray) 

Parameter

Code

import java.io.File
fun main()
val fileName = "file.txt"
val myFile = File(fileName)
val content = "Educative is the best platform."
myFile.writeBytes(content.toByteArray())
println("Written to the file")
>

Learn in-demand tech skills in half the time

Источник

kotlin-write-file

In this quick tutorial, we’ll learn about various ways of writing content into a file using Kotlin extension methods – available in its standard library.

2. Kotlin File Extensions

Kotlin provides various ways of writing into a file in the form of extension methods for java.io.File.

We’ll use several of these to demonstrate different ways in which we can achieve this using Kotlin:

  • writeText – lets us write directly from a String
  • writeBytes – enables us to write directly from a ByteArray
  • printWriter – provides us with a PrintWriter
  • bufferedWriter – allows us to write using a BufferedWriter

Let’s discuss them in more detail.

3. Writing Directly

Writing directly into a File from a given source is the simplest strategy that we can expect using Kotlin extension methods.

3.1. writeText

Probably the most straightforward extension method, writeText takes the content as a String argument and writes it directly into the specified file. The given content is text encoded in UTF-8 (default) or any other specified charset:

File(fileName).writeText(fileContent)

This method internally delegates on writeBytes as described below. But first, it converts the given content into an array of bytes using the specified charset.

3.2. writeBytes

Likewise, we can use bytes as an input. The method writeBytes takes a ByteArray as an argument and directly writes it into the specified file. This is useful when we have the contents as an array of bytes rather than plain text.

File(fileName).writeBytes(fileContentAsArray)

If the given file exists, it’s overwritten.

4. Writing into a File Using Writers

Kotlin also offers extension methods that provide us with a Java Writer instance.

4.1. printWriter

If we’d like to use a Java PrintWriter, Kotlin provides a printWriter function exactly for this purpose. With it, we can print formatted representations of objects to an OutputStream:

This method returns a new PrintWriter instance. Next, we can take advantage of the method use to handle it:

File(fileName).printWriter().use < out ->out.println(fileContent) >

With use, we can execute a function on the resource which gets closed after termination. The resource is closed irrespectively of whether the function executed successfully or threw an exception.

4.2. bufferedWriter

Likewise, Kotlin also provides a bufferedWriter function that provides us with a Java BufferedWriter.

Then, with it, we can write text to a character-output stream in a more efficient way.

File(fileName).bufferedWriter()

Similar to PrintWriter, this function returns a new BufferedWriter instance which, later, we can use to write the content of the file.

File(fileName).bufferedWriter().use < out ->out.write(fileContent) >

5. Conclusion

In this article, we saw different ways of writing into a file using Kotlin extension methods.

Finally, the source code for this article and the relevant test cases are available in the following GitHub repository.

Источник

Оцените статью