使用Kotlin创建一个新目录,Mkdir()不起作用

时间:2017-06-07 19:22:57

标签: android kotlin

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

我正在尝试使用Kotlin在Android设备上创建一个新目录,但函数mkdirs()不起作用。

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

我也尝试了这个,它没有创建一个新目录 欢迎任何帮助

2 个答案:

答案 0 :(得分:5)

这完全适用于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()
    }

  }
}

答案 1 :(得分:0)

您还可以使用“也”来执行此操作:

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