Kotlin append to file

Kotlin append to file

Appends the specified collection of char sequences lines to a file terminating each one with the platform’s line separator.

Appends the specified sequence of char sequences lines to a file terminating each one with the platform’s line separator.

appendText

Appends text to the content of this file using UTF-8 or the specified charset.

bufferedReader

Returns a new BufferedReader for reading the content of this file.

fun Path . bufferedReader (
charset : Charset = Charsets.UTF_8 ,
bufferSize : Int = DEFAULT_BUFFER_SIZE ,
vararg options : OpenOption
) : BufferedReader

bufferedWriter

Returns a new BufferedWriter for writing the content of this file.

fun Path . bufferedWriter (
charset : Charset = Charsets.UTF_8 ,
bufferSize : Int = DEFAULT_BUFFER_SIZE ,
vararg options : OpenOption
) : BufferedWriter

copyTo

Copies a file or directory located by this path to the given target path.

copyToRecursively

Recursively copies this directory and its content to the specified destination target path. Note that if this function throws, partial copying may have taken place.

fun Path . copyToRecursively (
target : Path ,
onError : ( source : Path , target : Path , exception : Exception ) -> OnErrorResult = < _, _, exception ->throw exception > ,
followLinks : Boolean ,
overwrite : Boolean
) : Path

fun Path . copyToRecursively (
target : Path ,
onError : ( source : Path , target : Path , exception : Exception ) -> OnErrorResult = < _, _, exception ->throw exception > ,
followLinks : Boolean ,
copyAction : CopyActionContext . ( source : Path , target : Path ) -> CopyActionResult = < src, dst ->src.copyToIgnoringExistingDirectory(dst, followLinks) >
) : Path

Источник

How to append text to file in Kotlin?

To append text to a file in Kotlin, we can use File.appendText() method.

There could be scenarios where you may need to add a debug line to the report, or some log file, etc. In such scenarios, Kotlin’s extension funtion to java.io.File, appendText(String text) helps to append text to the original file.

Syntax

The syntax of File.appendText() method is

fun File.appendText( ?text: String, ?charset: Charset = Charsets.UTF_8)
File(filename).appendText(textToBeAppended, charset)
Parameter Required / Optional Description
filename Required Name of the text file to which textToBeAppended is appended.
textToBeAppended Required The string which is appended to the specified file.
charset Optional The default Charset used is Charsets.UTF_8. You may specify any other Charset if required.

Examples

1. Append Text to File

Following is the content of the original file.

Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com.

In the following program, we append a string in content variable to the existing file file.txt.

import java.io.File fun main(args: Array)

Following is the content of file after appending string.

Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com. This is additional content added to the File.

Conclusion

In this Kotlin Tutorial, we learned how to append text to a file using File.appendText() method, with the help of examples.

Источник

Kotlin append to file

Returns a new BufferedWriter for writing the content of this file.

Читайте также:  Java process error messages

fun File . bufferedWriter (
charset : Charset = Charsets.UTF_8 ,
bufferSize : Int = DEFAULT_BUFFER_SIZE
) : BufferedWriter

copyRecursively

Copies this file with all its children to the specified destination target path. If some directories on the way to the destination are missing, then they will be created.

fun File . copyRecursively (
target : File ,
overwrite : Boolean = false ,
onError : ( File , IOException ) -> OnErrorAction = < _, exception ->throw exception >
) : Boolean

copyTo

Copies this file to the given target file.

fun File . copyTo (
target : File ,
overwrite : Boolean = false ,
bufferSize : Int = DEFAULT_BUFFER_SIZE
) : File

deleteRecursively

Delete this file with all its children. Note that if this operation fails then partial deletion may have taken place.

endsWith

Determines whether this file path ends with the path of other file.

Determines whether this file belongs to the same root as other and ends with all components of other in the same order. So if other has N components, last N components of this must be the same as in other. For relative other, this can belong to any root.

extension

Returns the extension of this file (not including the dot), or an empty string if it doesn’t have one.

forEachBlock

Reads file by byte blocks and calls action for each block read. Block has default size which is implementation-dependent. This functions passes the byte array and amount of bytes in the array to the action function.

Reads file by byte blocks and calls action for each block read. This functions passes the byte array and amount of bytes in the array to the action function.

fun File . forEachBlock (
blockSize : Int ,
action : ( buffer : ByteArray , bytesRead : Int ) -> Unit )

forEachLine

Reads this file line by line using the specified charset and calls action for each line. Default charset is UTF-8.

inputStream

Constructs a new FileInputStream of this file and returns it as a result.

invariantSeparatorsPath

Returns path of this File using the invariant separator ‘/’ to separate the names in the name sequence.

isRooted

Determines whether this file has a root or it represents a relative path.

nameWithoutExtension

Returns file’s name without an extension.

normalize

Removes all . and resolves all possible .. in this file name. For instance, File(«/foo/./bar/gav/../baaz»).normalize() is File(«/foo/bar/baaz») .

outputStream

Constructs a new FileOutputStream of this file and returns it as a result.

printWriter

Returns a new PrintWriter for writing the content of this file.

readBytes

Gets the entire content of this file as a byte array.

reader

Returns a new FileReader for reading the content of this file.

readLines

Reads the file content as a list of lines.

readText

Gets the entire content of this file as a String using UTF-8 or specified charset.

relativeTo

Calculates the relative path for this file from base file. Note that the base file is treated as a directory. If this file matches the base file, then a File with empty path will be returned.

relativeToOrNull

Calculates the relative path for this file from base file. Note that the base file is treated as a directory. If this file matches the base file, then a File with empty path will be returned.

relativeToOrSelf

Calculates the relative path for this file from base file. Note that the base file is treated as a directory. If this file matches the base file, then a File with empty path will be returned.

Читайте также:  Python on windows how to start

resolve

Adds relative file to this, considering this as a directory. If relative has a root, relative is returned back. For instance, File(«/foo/bar»).resolve(File(«gav»)) is File(«/foo/bar/gav») . This function is complementary with relativeTo, so f.resolve(g.relativeTo(f)) == g should be always true except for different roots case.

Adds relative name to this, considering this as a directory. If relative has a root, relative is returned back. For instance, File(«/foo/bar»).resolve(«gav») is File(«/foo/bar/gav») .

Источник

Read and write files in Kotlin

In Kotlin, to check if the file already exists, use File.exists(), exists() returns a Boolean value. It returns true if the file exists and false if the file does not exist.

import java.io.File fun main(args: Array) < val filename = "chercher tech.txt" var fileObject = File(filename) var fileExists = fileObject.exists() if(fileExists)< print("$filename file does exist.") >else < print("$filename file does not exist.") >>

Kotlin Create File

In Kotlin, a new file could be created using

We will learn about how to use these file writing methods in kotlin .

File.createNewFile()

File.createNewFile() creates a new file if it does not exist already and returns a Boolean value of true. If the file exists at the path provided, then createNewFile() functions returns false. The file created is empty and has zero bytes written to it.

createNewFile() is the way in which the existing file will not be overridden. Remaining ways will overwrite the file if it exists.

In the below example, we will try to create a new file and then we try to override it.

import java.io.File fun main(args: Array) < val fileName = "cherchertech.txt" var fileObject = File(fileName) // create a new file val isNewFileCreated :Boolean = fileObject.createNewFile() if(isNewFileCreated)< println("$fileName is created successfully.") >else < println("$fileName already exists.") >// try creating a file that already exists val isFileCreated :Boolean = fileObject.createNewFile() if(isFileCreated) < println("$fileName is created successfully.") >else < println("$fileName already exists.") >>

writeText()

writeText() function creates a new file if it does not exist already and writes the text (string argument) to the file. If an empty string is provided, the file is created and nothing is written to it.

if file exists in the path already then the file will be overridden, Sets the content of this file as text encoded using UTF-8 or charset specified by the user.

import java.io.File fun main(args: Array) < val fileName = "chercher tech.txt" var fileObject = File(fileName) // create a new file fileObject.writeText("This is some text for file writing operations") >

writeBytes()

writeBytes() function creates a new file and writes an array of bytes provided to the file created. If this file already exists, it becomes overwritten.

Read files in Kotlin

We can read contents of a file in Kotlin either by using standard methods of the java.io.File class, or the methods that Kotlin provides as an extension to java.io.File.

chercher tech.txt file content

Chercher tech provides the tutorials for the future technologies, We are writing an article one per day Actually the author is not a developer, he is a tester first author thought to write a tutorial only for selenium then he thought for protractor python and then UI path now writing kotlin file operations

bufferedReader()

bufferedReader() to read contents of a file into BufferedReader

import java.io.File fun main(args: Array) < val file = File("chercher tech.txt") val bufferedReader = file.bufferedReader() val text:List = bufferedReader.readLines() for(line in text)< println(line) >>

forEachLine()

forEachLine() reads this file line by line using the specified charset and calls the action for each line. The default charset is UTF-8

import java.io.File fun main(args: Array) < val file = File("chercher tech.txt") file.forEachLine < println(it) >>

inputStream()

inputStream() Constructs a new FileInputStream of this file and returns it as a result.

import java.io.File import java.io.InputStream import java.nio.charset.Charset fun main(args: Array) < val file = File("chercher tech.txt") var ins:InputStream = file.inputStream() // read contents of IntputStream to String var content = ins.readBytes().toString(Charset.defaultCharset()) println(content) >

readBytes()

readBytes() Gets the entire content of this file as a byte array. This method is not recommended on huge files. It has an internal limitation of 2 GB byte array size.

import java.io.File fun main(args: Array) < val file = File("chercher tech.txt") var bytes:ByteArray = file.readBytes() for(byte in bytes)< print(byte.toChar()) >>

readLines()

readLines() Reads the file content as a list of lines. Do not use this function for huge files.

import java.io.File fun main(args: Array) < val file = File("chercher tech.txt") var lines:List = file.readLines() for(line in lines)< println(line) >>

readText()

readText() Gets the entire content of this file as a String using UTF-8 or charset specified by the user

import java.io.File fun main(args: Array)

Write content to files

Creating a file is different from writing a file, we can write content to file while creating it but sometime we may want to write to a file which is already present in the file system.

Читайте также:  Минимум на стеке python

We can write a using writeText() function present in the File class

import java.io.File fun main(args: Array) < val filename = "chercher tech.txt" // content to be written to file var content:String = "dummy text to show writing to file in koltin chercher tech" File(filename).writeText(content) >
import java.io.PrintWriter fun main(args: Array) < val filename = "chercher tech.txt" // content to be written to file var content:String = "dummy text to show writing to file in koltin chercher tech" // using java class java.io.PrintWriter val writer = PrintWriter(filename) writer.append(content) writer.close() >

printWriter() function calls the PrintWriter constructor internally

import java.io.File fun main(args: Array) < val filename = "chercher tech.txt" // content to be written to file var content:String = "dummy text to show writing to file in koltin chercher tech" // write content to file File(filename).printWriter().use < param ->param.println(content) > >

Append content to a file in kotlin

What is the difference between simply writing to a file vs appending data to a file?
In the case of writing to a file, a program can start writing from the start but in the case of appending text , you start writing from the end of the file.

You can append text into an existing file in Kotlin by opening a file using appendText() function in File class. One of the common examples of appending text to file is logging

import java.io.File fun main(args: Array) < val filename = "chercher tech.txt" // content to be written to file var content:String = "dummy text to show writing to file in kotlin chercher tech" // write content to file File(filename).writeText(content) File(filename).appendText("ppppppp") >

Источник

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