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

ble*_*uel 4 android kotlin

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

我正在尝试使用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)
Run Code Online (Sandbox Code Playgroud)

我也尝试过,它没有建立新目录,欢迎任何帮助

Aru*_*kar 7

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

  }
}
Run Code Online (Sandbox Code Playgroud)

  • 当问题不起作用时,是什么让这个起作用?它们看起来很相似——是额外的斜线吗? (2认同)

小智 5

您还可以使用以下also方法执行此操作:

File("path_to_file").also {
                              file -> file.parentFile.mkdirs()
                          }.writeBytes(bytes)
Run Code Online (Sandbox Code Playgroud)