簡體   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