在Android中写入文本文件

时间:2019-04-14 05:24:37

标签: android kotlin text-files file-writing

我尝试使用代码from MallikarjunM, 但这对我不起作用:-(。 我很少用一个textViev“ pokusnejText”将其重写为我的基本Android Studio项目,其中包含空的活动。

这是我的代码MainActivity.kt:

package com.example.zapisdosouboru

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.TextView
import java.io.File
import java.io.PrintWriter

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val pokusnejText = findViewById<TextView>(R.id.pokusnejText)


        var answer : String = ""
        val sd_main = File(Environment.getExternalStorageDirectory().toString() + "/smazat" )
        var success = true
        if (!sd_main.exists()) {
            success = sd_main.mkdir()
            if (success) {
                answer = "folder created"
            } else {
                answer = "folder can not be created"
            }
        }

        if (success) {
            val sd = File("testingFile.txt")

            if (!sd.exists()) {
                success = sd.mkdir()
            }

            if (success) {
                // directory exists or already created
                val dest = File(sd, "testingFile.txt")

                try {
                    // response is the data written to file
                    PrintWriter(dest).use { out -> out.println(answer) }
                    answer = "writed to" + sd.toString()
                } catch (e: Exception) {
                    answer = "can not be written"
                }

            } else {
                answer = "folder or file does not exists"
            }
        }
        pokusnejText.text = answer
    }
}

这是我的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.zapisdosouboru">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>

首先我要重写的是

val sd_main = File(Environment.getExternalStorageDirectory()+"/yourlocation")

val sd_main = File(Environment.getExternalStorageDirectory().toString() + "/yourlocation" )

因为没有toString()加上红色标记为... 但它仍然无法正常工作,并回答它无法创建文件夹... 我已经在带有Android 6.0的Android Studio模拟器中尝试过

一些其他问题: 我对函数File()在代码中一次使用一个参数而第二次使用两个参数感到非常困惑。 对于Kotlin是否存在一些类似http://www.cplusplus.com/的网页-我找不到像c ++那样有用的东西。

感谢帮助 fik236

2 个答案:

答案 0 :(得分:0)

您说的是您在Android 6的模拟器上尝试过该操作。您是否在写入外部存储之前explicitly ask获得了WRITE_EXTERNAL_STORAGE的许可?执行此代码后,logcat中的输出是什么?应该在那里说由于“权限被拒绝”而无法创建文件

对于类似于cplusplus.com的站点,可以肯定的是,Kotlin language reference具有与cpp.com相同的功能,我想说它会更好,因为它包含对书籍,在线课程等的引用。

答案 1 :(得分:0)

感谢MarošŠeleng,我掌握了一些工作代码。就是这样:

package com.example.zapisdosouboru

import android.Manifest
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.ActivityCompat
import android.widget.TextView
import java.io.File
import java.io.PrintWriter

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)



        // Here, thisActivity is the current activity
        if (checkSelfPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            // Permission has already been granted
        }

        val pokusnejText = findViewById<TextView>(R.id.pokusnejText)


        var answer : String = ""
        val sd_main = File(Environment.getExternalStorageDirectory() , "smazat" )
        var success = true
        if (!sd_main.exists()) {
            success = sd_main.mkdir()
            if (success) {
                answer = "folder created"
            } else {
                answer = "folder can not be created"
            }
        }

        if (success) {
            val sd = File(sd_main,"testingFile.txt")

            if (!sd.isFile()) {
                success = sd.createNewFile()
            }

            if (success) {
                // directory exists or already created

                try {
                    answer = "writed to" + sd.toString()
                    PrintWriter(sd).use { out -> out.println("testing text") }

                } catch (e: Exception) {
                    answer = "can not be written"
                }

            } else {
                answer = "folder or file does not exists"
            }
        }
        pokusnejText.text = answer
    }
}