Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

kotlin

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

like image 692
blesson Samuel Avatar asked Jun 07 '17 19:06

blesson Samuel


People also ask

How to create directory in Android studio?

Select layouts , right-click and select New → Folder → Res Folder. This resource folder will represent a “feature category” that you want. You can easily create any type of file/folder in Android Studio.

How do I create a folder in Android media android 11?

context. getExternalMediaDirs() will return you all the folders from media folder and when you call that it will create a folder with your app's package name all you have to do is identify packagename and get your folder path. This function will return you full path to your folder inside media folder.


2 Answers

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()
    }

  }
}
like image 187
Arun Shankar Avatar answered Sep 18 '22 19:09

Arun Shankar


You can also use also to do this:

File("path_to_file").also {
                              file -> file.parentFile.mkdirs()
                          }.writeBytes(bytes)
like image 33
Rundom Avatar answered Sep 20 '22 19:09

Rundom