本文概述
- 写入外部存储中的文件
- 从外部存储读取文件内容
- 外部存储访问权限
- Kotlin Android读写外部存储示例
在访问应用程序外部存储中的文件之前, 我们应检查设备中外部存储的可用性。
写入外部存储中的文件 【Kotlin Android读写外部存储】java.io包提供openFileOutput()方法, 该方法返回FileOutputStream类的实例, 以将文件写入设备的外部存储中。通过调用getExternalFilesDir()获取仅由你的应用程序使用的目录。要将数据写入文件, 请调用FileOutputStream .write()方法。
var myExternalFile:File = File(getExternalFilesDir(filepath), fileName) try {val fileOutPutStream = FileOutputStream(myExternalFile)fileOutPutStream.write(fileContent.toByteArray())fileOutPutStream.close() } catch (e: IOException) {e.printStackTrace() }
从外部存储读取文件内容 java.io包提供了openFileInput()方法, 该方法返回FileInputStream类的实例, 并从设备的外部存储读取文件。要从文件读取数据, 请调用BufferedReader()。readLine()。
var myExternalFile:File = File(getExternalFilesDir(filepath), fileName)val filename = fileName.text.toString()myExternalFile = File(getExternalFilesDir(filepath), filename) var fileInputStream =FileInputStream(myExternalFile)var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)val stringBuilder: StringBuilder = StringBuilder()var text: String? = nullwhile ({ text = bufferedReader.readLine();
text }() != null) {stringBuilder.append(text)}fileInputStream.close()
外部存储访问权限 在AndroidManifest.xml文件中添加以下权限。
<
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Kotlin Android读写外部存储示例 在此示例中, 我们将数据写入外部存储设备中的文件, 并从同一外部存储设备读取相同的文件内容。
activity_main.xml
在activity_main.xml文件中添加以下代码。在此文件中, 为输入文件名, 文件内容添加两个EditText, 并为保存和查看文件内容添加两个Button。
<
?xml version="1.0" encoding="utf-8"?>
<
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="example.srcmini.com.kotlinexternalstoragereadwrite.MainActivity">
<
TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView2"android:layout_alignParentTop="true"android:layout_alignStart="@+id/textView2"android:layout_marginTop="68dp"android:text="File Name"android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.027"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintVertical_bias="0.065" />
<
TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBottom="@+id/editTextData"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_marginBottom="36dp"android:layout_marginLeft="50dp"android:layout_marginStart="50dp"android:text="File Data"android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.027"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView"app:layout_constraintVertical_bias="0.167" />
<
EditTextandroid:id="@+id/editTextFile"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/editTextData"android:layout_alignStart="@+id/editTextData"android:layout_alignTop="@+id/textView"android:ems="10"android:inputType="none" />
<
EditTextandroid:id="@+id/editTextData"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentEnd="true"android:layout_alignParentRight="true"android:layout_below="@+id/editTextFile"android:layout_marginEnd="37dp"android:layout_marginRight="37dp"android:layout_marginTop="30dp"android:ems="10"android:inputType="none"android:lines="5" />
<
Buttonandroid:id="@+id/button_save"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_marginBottom="68dp"android:layout_toLeftOf="@+id/editTextData"android:layout_toStartOf="@+id/editTextData"android:text="Save" />
<
Buttonandroid:id="@+id/button_view"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBottom="@+id/button_save"android:layout_alignEnd="@+id/editTextData"android:layout_alignRight="@+id/editTextData"android:layout_marginEnd="43dp"android:layout_marginRight="43dp"android:text="View" />
<
/RelativeLayout>
MainActivity.kt
在MainActivity.kt类中添加以下代码。在此类中, 我们将通过单击保存按钮将文件名和数据保存在外部存储器中, 并通过单击查看按钮来检索文件内容。
package example.srcmini.com.kotlinexternalstoragereadwriteimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport android.os.Environmentimport java.io.*class MainActivity : AppCompatActivity() {private val filepath = "MyFileStorage"internal var myExternalFile: File?=nullprivate val isExternalStorageReadOnly: Boolean get() {val extStorageState = Environment.getExternalStorageState()return if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {true} else {false}}private val isExternalStorageAvailable: Boolean get() {val extStorageState = Environment.getExternalStorageState()return if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {true} else{false}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val fileName = findViewById(R.id.editTextFile) as EditTextval fileData = http://www.srcmini.com/findViewById(R.id.editTextData) as EditTextval saveButton = findViewById<
Button>
(R.id.button_save) as Buttonval viewButton = findViewById(R.id.button_view) as ButtonsaveButton.setOnClickListener(View.OnClickListener {myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())try {val fileOutPutStream = FileOutputStream(myExternalFile)fileOutPutStream.write(fileData.text.toString().toByteArray())fileOutPutStream.close()} catch (e: IOException) {e.printStackTrace()}Toast.makeText(applicationContext,"data save", Toast.LENGTH_SHORT).show()})viewButton.setOnClickListener(View.OnClickListener {myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())val filename = fileName.text.toString()myExternalFile = File(getExternalFilesDir(filepath), filename)if(filename.toString()!=null &
&
filename.toString().trim()!=""){var fileInputStream =FileInputStream(myExternalFile)var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)val stringBuilder: StringBuilder = StringBuilder()var text: String? = nullwhile ({ text = bufferedReader.readLine();
text }() != null) {stringBuilder.append(text)}fileInputStream.close()//Displaying data on EditTextToast.makeText(applicationContext, stringBuilder.toString(), Toast.LENGTH_SHORT).show()}})if (!isExternalStorageAvailable || isExternalStorageReadOnly) {saveButton.isEnabled = false}}}
AndroidManifest.xml
<
?xml version="1.0" encoding="utf-8"?>
<
manifest xmlns:android="http://schemas.android.com/apk/res/android"package="example.srcmini.com.kotlinexternalstoragereadwrite">
<
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<
applicationandroid: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>
输出:
文章图片
文章图片
文章图片
文章图片
推荐阅读
- Kotlin Android读写内部存储
- Kotlin Android ListView
- Kotlin Android弹出菜单
- Kotlin Android选项菜单
- Kotlin Android通知
- Kotlin Android媒体播放器
- Kotlin Android Google Map当前位置
- Kotlin Android隐式Intent
- 使用URL的Kotlin Android JSON解析