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

前端 未结 2 1484
梦毁少年i
梦毁少年i 2021-02-14 04:58
var filename = \"blesson.txt\"
var wallpaperDirectory = File(\"/sdcard/Wallpaper\")
 wallpaperDirectory.mkdirs()
val outputFile = File(wallpaperDirectory, filename)
val          


        
相关标签:
2条回答
  • 2021-02-14 05:23

    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()
        }
    
      }
    }
    
    0 讨论(0)
  • 2021-02-14 05:26

    You can also use also to do this:

    File("path_to_file").also {
                                  file -> file.parentFile.mkdirs()
                              }.writeBytes(bytes)
    
    0 讨论(0)
提交回复
热议问题