Jaber2599
Jaber2599

Reputation: 101

Kotlin: How to save file in a directory? Having errors

Having problems with my code, So I am currently trying to create a new directory and also store a text file within that folder I have created, I looked at a couple of examples but it seems like they only focus on a specific thing like how to create a file or a folder but never how to utilise both. How can I achieve this? I keep hitting exception errors when I try doing different methods, thanks!

val newFile : Int = 1
          val fileString = "nameData"

          //so we are creating variable to store the directory information
          
          val folderDir = File("G:\\Random Projects\\JVM\\database\\Collection 1")
          //we use that variable to create a File class which will create a folder called nameData
          //this will also be stored in another variable called f
          
          val f = File(folderDir, "nameData")
          
          //this will create the actual folder based on the variable information
          f.mkdir()

          //creating file
          try {
               val fo = FileWriter(fileString, true)
               fo.write(a)
               fo.close()
          } catch (ex:Exception) {
               println("Something Went Wrong When Creating File!!")
          }

Upvotes: 0

Views: 1264

Answers (1)

Adam Arold
Adam Arold

Reputation: 30528

The problem is that you probably don't have the whole folder structure created, that's why you usually use the mkdirs (note the s at the end) function. You can then use the writeBytes function to write the content:

val fileString = "nameData"
val folderDir = File("myfolder")
val f = File(folderDir, "nameData")
f.parentFile.mkdirs()
f.writeBytes(fileString.toByteArray())

Upvotes: 1

Related Questions