繁体   English   中英

在android中写入文本文件

[英]writing into text file in android

我尝试过来自MallikarjunM的代码,但它对我不起作用:-(。我把它重写到我的基本Android Studio项目,其中包含一个textViev“pokusnejText”的空活动。

这是我的代码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 6.0

一些额外的问题:我很困惑函数File()在代码中使用一次带一个参数,第二次用两个。 Kotlin是否存在类似http://www.cplusplus.com/的网页 - 我找不到任何对c ++有帮助的东西。

感谢您的帮助fik236

你是说你在Android 6的模拟器上试过这个。你在写入外部存储之前是否明确要求 WRITE_EXTERNAL_STORAGE权限? 这段代码执行时logcat的输出是什么? 它应该在那里说它无法创建文件,因为'权限被拒绝'

关于类似于cplusplus.com的网站,当然,有Kotlin语言参考 ,它具有与cpp.com相同的功能,我认为它更好,因为它包含对书籍,在线课程等的参考。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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