(Kotlin) 如何在 android studio 中写入文件?

发布于 2025-01-15 21:53:01 字数 3195 浏览 0 评论 0原文

我正在尝试写入在应用程序中创建的文件,但是当我打开该文件时,其中没有任何内容。到目前为止,我尝试了几种方法,这是尝试写入文件的最新尝试。我之前使用过 fileoutputstream,但文件已写入内部存储,在设备上的文件管理器中无法查看。我在实施中做错了什么吗?

        //Function call for creating and generating the python code
        generate.setOnClickListener{
            //Getting Storage Permissions
            checkPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE)
            checkPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE)

            val file = "file.txt"
            var path = getExternalFilesDir("Written Files")
            var fileOut = File(path, file)
            fileOut.delete()
            
            try
            {

                fileOut.createNewFile()                
                PrintWriter(openFileOutput(file, Context.MODE_PRIVATE)).use{
                        it.println("Hello World!")
                    }
            }
            //Catching any file errors that could occur
            catch(e: FileNotFoundException)
            {
                e.printStackTrace()
            }
            catch(e:NumberFormatException)
            {
                e.printStackTrace()
            }
            catch(e: IOException)
            {
                e.printStackTrace()
            }
            catch(e:Exception)
            {
                e.printStackTrace()
            }
            //Creating display message when generating the code
            Toast.makeText(this, "Generating", Toast.LENGTH_SHORT).show()

        }

权限功能

    private fun checkPermissions(permission:String, requestCode:Int)
    {
        if(ContextCompat.checkSelfPermission(this@MainActivity, permission)==PackageManager.PERMISSION_DENIED)
        {
            //Get Permission
            ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission), requestCode)

        }
        else
        {
            Toast.makeText(this@MainActivity, "Permission Already Granted", Toast.LENGTH_LONG)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if(requestCode==CAMERA_PERMISSION_CODE)
        {
            if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this@MainActivity, "Camera Permission Granted", Toast.LENGTH_SHORT)
            }
            else
            {
                Toast.makeText(this@MainActivity, "Camera Permission Denied", Toast.LENGTH_SHORT)
            }
        }
        else if (requestCode==STORAGE_PERMISSION_CODE)
        {
            if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this@MainActivity, "Storage Permission Granted", Toast.LENGTH_SHORT)
            }
            else
            {
                Toast.makeText(this@MainActivity, "Storage Permission Denied", Toast.LENGTH_SHORT)
            }
        }
    }
}

I'm trying to write to a file that I created in my app but when I open the file, there's nothing in it. I tried several methods so far and this is the latest attempt at trying to write to a file. I was using the fileoutputstream before but the file was getting written to internal storage which is not viewable in the File Manager on the device. Am I doing something wrong in my implementation?

        //Function call for creating and generating the python code
        generate.setOnClickListener{
            //Getting Storage Permissions
            checkPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE)
            checkPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE)

            val file = "file.txt"
            var path = getExternalFilesDir("Written Files")
            var fileOut = File(path, file)
            fileOut.delete()
            
            try
            {

                fileOut.createNewFile()                
                PrintWriter(openFileOutput(file, Context.MODE_PRIVATE)).use{
                        it.println("Hello World!")
                    }
            }
            //Catching any file errors that could occur
            catch(e: FileNotFoundException)
            {
                e.printStackTrace()
            }
            catch(e:NumberFormatException)
            {
                e.printStackTrace()
            }
            catch(e: IOException)
            {
                e.printStackTrace()
            }
            catch(e:Exception)
            {
                e.printStackTrace()
            }
            //Creating display message when generating the code
            Toast.makeText(this, "Generating", Toast.LENGTH_SHORT).show()

        }

Permission Functions

    private fun checkPermissions(permission:String, requestCode:Int)
    {
        if(ContextCompat.checkSelfPermission(this@MainActivity, permission)==PackageManager.PERMISSION_DENIED)
        {
            //Get Permission
            ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission), requestCode)

        }
        else
        {
            Toast.makeText(this@MainActivity, "Permission Already Granted", Toast.LENGTH_LONG)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if(requestCode==CAMERA_PERMISSION_CODE)
        {
            if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this@MainActivity, "Camera Permission Granted", Toast.LENGTH_SHORT)
            }
            else
            {
                Toast.makeText(this@MainActivity, "Camera Permission Denied", Toast.LENGTH_SHORT)
            }
        }
        else if (requestCode==STORAGE_PERMISSION_CODE)
        {
            if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this@MainActivity, "Storage Permission Granted", Toast.LENGTH_SHORT)
            }
            else
            {
                Toast.makeText(this@MainActivity, "Storage Permission Denied", Toast.LENGTH_SHORT)
            }
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文