How to create file kotlin

createTempFile

Deprecated: Avoid creating temporary files in the default temp location with this function due to too wide permissions on the newly created file. Use kotlin.io.path.createTempFile instead or resort to java.io.File.createTempFile.

Creates a new empty file in the specified directory, using the given prefix and suffix to generate its name.

If prefix is not specified then some unspecified string will be used. If suffix is not specified then «.tmp» will be used. If directory is not specified then the default temporary-file directory will be used.

The prefix argument, if specified, must be at least three characters long. It is recommended that the prefix be a short, meaningful string such as «job» or «mail».

To create the new file, the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform.

Note: if the new file is created in a directory that is shared with all users, it may get permissions allowing everyone to read it, thus creating a risk of leaking sensitive information stored in this file. To avoid this, it’s recommended either to specify an explicit parent directory that is not shared widely, or to use alternative ways of creating temporary files, such as java.nio.file.Files.createTempFile or the experimental createTempFile function in the kotlin.io.path package.

Читайте также:  Как получить массив пикселей python

Exceptions

IOException — in case of input/output error.

IllegalArgumentException — if prefix is shorter than three symbols.

Return a file object corresponding to a newly-created file.

Источник

Kotlin – Create File – Examples

Kotlin Create File – In Kotlin, new file could be created using File.createNewFile(), File.writeText(text :String), Files.writeBytes() etc. There are many other ways to create a file in Kotlin. We shall look into the code implementation for some of them using example Kotlin programs.

Create File using File.createNewFile()

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

Using File.createNewFile() is the best and safest procedure to create a new file. Most of the other methods, we go through in this tutorial, would overwrite the file if it exists which may result in the loss of existing data which is not desired in some cases.

Example

In the following example, we try to create a new file with name data.txt. For the first time, the file is created and true is returned. When we try to create the file for second time, as file data.txt is already created, we get false.

Main.kt

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

Create File using File.writeText()

File.writeText() 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. By default the file is encoded as UTF-8. Passing any other charset as second argument encodes the file accordingly.

Note : In case, the file already exists, it is overwritten and the existing data is lost.

Use this method if you are sure that the file does not exist already or overwriting the existing data does not affect your application.

Example

In this example, we will use File.writeText() to create a new File.

Main.kt

import java.io.File fun main(args: Array) < val fileName = "data.txt" var file = File(fileName) // create a new file file.writeText("") >

We have given an empty string, as argument to writeText(), to write data to file. You may provide the string you would like to write into this file.

Create File using File.writeText()

File.writeBytes() creates a new file if it does not exist already and writes the raw bytes of the ByteArray provided to the file created. If an empty ByteArray is provided, the file is created and nothing is written to it.

Note : In case, the file already exists, it is overwritten and the existing data is lost.

Use this method if you are sure that the file does not exist already or overwriting the existing data does not affect your application.

Example

In this example, we will use File.writeBytes() to create a new File.

import java.io.File fun main(args: Array) < val fileName = "data.txt" var file = File(fileName) // create a new file file.writeBytes(ByteArray(0)) >

We have given an empty byte array, as argument to writeBytes(), to write data to file. You may provide the ByteArray you would like to write into this file.

Conclusion

In this Kotlin Tutorial – Kotlin Create File, we have learnt how to create a new file using File.createNewFile(). Also we have seen how File.writeText() and File.writeBytes() could be used to create a file and the side effects of overwriting the existing file if it already exists, with ample Examples.

Источник

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.

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") >

Источник

Kotlin File Handling

In this tutorial we will discuss about basics of file handling in Kotlin. Files are used to persist data in memory as after execution of program the data is lost if it is not stored.

There are many ways to create a file, read and write in a file. We’ll discuss some of them briefly.

Kotlin Create a file

Generally in many write methods a file is created itself but we’ll see a method to create a file. We’ll use File class available in java.io package. The constructor takes file name as the argument. We’ll use createNewFile() method to create a file.

If a file with given filename does not exists, createNewFile() method will create a new file and returns true. If a file with filename already exits, it will return false:

import java.io.File fun main() < val fileName = "Demo.txt" // Create file object val file = File(fileName) // Create file var isCreated = file.createNewFile() if (isCreated) println("File is created") else println("File is not created") // Again create file isCreated = file.createNewFile() if (isCreated) println("File is created") else println("File is not created") >

File is created
File is not created

We can also check existence of file using file.exists() method

Kotlin Writing to a File

We can write data in a file using writeText() method.

  • It will take String as an argument and writes it into the file.
  • It will create a new file if no file exists with specified name.
  • If file already exists, it will replace the file.
  • The given data is first encoded using UTF-8 charset by default. We can also specify any other charset.
import java.io.File fun main()

If we check the Demo.txt file we will see only Bye world in it. It is because writeText() will replace all the content present in file. If we wants to prevent the present data from getting lost, we can use appendText() function instead of writeText() function.

Kotlin Read from a file

For reading content line by line we can use forEachLine() method. It will read data line by line from the file.

import java.io.File fun main() < val fileName = "Demo.txt" val file = File(fileName) file.forEachLine < println(it) >>

We can also use readText() function to read data from a file:

import java.io.File fun main()

Summary

In this tutorial we discussed basic methods of creating a file, reading data from it and writing data to it.

Источник

How to create a text file and insert data to that file on Android using Kotlin?

This example demonstrates how to create a text file and insert data to that file on Android using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.kt

import android.content.Context import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import java.io.FileOutputStream import java.io.OutputStreamWriter class MainActivity : AppCompatActivity() < lateinit var editText: EditText override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" editText = findViewById(R.id.editText) >fun saveTextFile(view: View) < try < val fileOutputStream: FileOutputStream = openFileOutput("mytextfile.txt", Context.MODE_PRIVATE) val outputWriter = OutputStreamWriter(fileOutputStream) outputWriter.write(editText.text.toString()) outputWriter.close() //display file saved message Toast.makeText(baseContext, "File saved successfully!", Toast.LENGTH_SHORT).show() >catch (e: Exception) < e.printStackTrace() >> >

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Источник

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