单击按钮上的Kotlin打开文件

时间:2018-04-11 17:11:34

标签: kotlin

我是Kotlin的新手。有人可以告诉我如何点击按钮打开文件?是否有一些命令:

Button.setOnAction {
File.Open(*//specified file path*)  
        }

我正在使用 Kotlin进行Java开发而不是使用andriod。我有一个 .fxml 文件,我已经定义了这个按钮,我需要在kotlin(.kt)文件中定义上述功能。谢谢。

2 个答案:

答案 0 :(得分:1)

在您的活动中

btnBack.setOnClickListener {

    val intent = Intent()
            .setType("*/*")
            .setAction(Intent.ACTION_GET_CONTENT)

    startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)

}

仍然在您的活动中,插入此内容以捕获结果

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == 111 && resultCode == RESULT_OK) {
        val selectedFile = data?.data //The uri with the location of the file
    }
}

reference

答案 1 :(得分:0)

如果您需要使用此selectedFile路径(@Rizkita答案)来读取文本文件,请在onActivityResultfunction中添加类似以下内容(Kotlin):

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 111 && resultCode == AppCompatActivity.RESULT_OK) {
            val selectedFile = data?.data //The uri with the location of the file

            // Get the File path from the Uri

            println(selectedFile?.lastPathSegment)
            val path = selectedFile?.lastPathSegment.toString().removePrefix("raw:")
            println(path)
            text_reader.setText(getTextContent(path))
        }
    }


fun getTextContent(pathFilename: String): String {

    val fileobj = File( pathFilename )

    if (!fileobj.exists()) {

        println("Path does not exist")

    } else {

        println("Path to read exist")
    }

    println("Path to the file:")
    println(pathFilename)

    if (fileobj.exists() && fileobj.canRead()) {

        var ins: InputStream = fileobj.inputStream()
        var content = ins.readBytes().toString(Charset.defaultCharset())
        return content

    }else{

        return "Some error, Not found the File, or app has not permissions: " + pathFilename
    }
}
  

请注意,在我的示例中,text_reader只是.xml布局文件中TextView对象的ID。