blesson Samuel
blesson Samuel

Reputation: 421

Creating a new directory using Kotlin, Mkdir() doesn't work

var filename = "blesson.txt"
var wallpaperDirectory = File("/sdcard/Wallpaper")
 wallpaperDirectory.mkdirs()
val outputFile = File(wallpaperDirectory, filename)
val fos = FileOutputStream(outputFile)

I am trying to make a new directory on an Android device using Kotlin, but the function mkdirs() doesn't work.

var filename = "blesson.txt"
var wallpaperDirectory = File(Environment.getExternalStorageDirectory().absolutePath)//("/sdcard/Wallpaper")
wall
val outputFile = File(wallpaperDirectory, filename)
val fos = FileOutputStream(outputFile)

I have tried this also, it is not making a new directory Any help is welcome

Upvotes: 11

Views: 20716

Answers (2)

Rundom
Rundom

Reputation: 87

You can also use also to do this:

File("path_to_file").also {
                              file -> file.parentFile.mkdirs()
                          }.writeBytes(bytes)

Upvotes: 5

Arun Shankar
Arun Shankar

Reputation: 2295

This works perfectly on Kotlin

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var filename = "blesson.txt"
    // create a File object for the parent directory
    val wallpaperDirectory = File("/sdcard/Wallpaper/")
    // have the object build the directory structure, if needed.
    wallpaperDirectory.mkdirs()
    // create a File object for the output file
    val outputFile = File(wallpaperDirectory, filename)
    // now attach the OutputStream to the file object, instead of a String representation
    try {
      val fos = FileOutputStream(outputFile)
    } catch (e: FileNotFoundException) {
      e.printStackTrace()
    }

  }
}

Upvotes: 19

Related Questions