简体   繁体   中英

writing into text file in android

I have tried code from MallikarjunM , but it does not work for me :-(. I have it little rewrite it to my basic Android Studio project with empty activity with one textViev "pokusnejText".

here is my code 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
    }
}

and here is my 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>

first what I have rewrite was

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

to

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

because without toString() was plus marked red ... but it still does not work and answers that it can not create the folder... I have tried it in Android Studio emulator with android 6.0

Some additional questions: I am very confused with function File() used in code one time with one parameter and second times with two. Does exists for Kotlin some web page similar http://www.cplusplus.com/ - I can not find any so helpful as for c++.

Thanks for help fik236

You are saying you tried that on emulator of Android 6. Did you explicitly ask for WRITE_EXTERNAL_STORAGE permission before writing into the external storage? What's the output in the logcat when this code executes? It should be there saying that it cannot create the file because of 'permission denied'

Regarding site similar to cplusplus.com, sure, there is Kotlin language reference which bears the same function that cpp.com and I'd say it is even better as it contains references to books, online courses, etc.

thanks to Maroš Šeleng I have some how working code. Here is it:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM