1.代码
package com.example.listadapter;
import android.content.Context;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileHelper {
// 文件写操作函数
static void write(Context context, String filename, String content){
try {
FileOutputStream fileOutputStream = context.openFileOutput(filename+".txt", Context.MODE_APPEND);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 文件读操作函数
static String[] read(Context context,String filename) {
String[] data = new String[0];
try {
File file = new File(context.getFilesDir(),filename+".txt");
FileReader fileReader = new FileReader(file.getPath());
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> stringArrayList = new ArrayList<>();
String line;
while((line = bufferedReader.readLine()) != null){
stringArrayList.add(line);
}
fileReader.close();
data = (String[]) stringArrayList.toArray(new String[stringArrayList.size()]);
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
首先安排上代码了,其实java的文件读取,我还不会,这也只是网上抄来的,但是这里还是有些注意事项的,
因为不知道怎么在空格直接读取信息,比如有as ssa sds,先读as,下一个是ssa这样,而且时间的格式是2021年10月29日 星期五 16:13:31,中间有空格,所以我索性就让每个数据都占一行,直接进行读取一整行就可以了。
这里我们不说读的,我们直说写的,
写的时候,打开文件的时候有几种打开方式,目前我用到了两种方式。
Context.MODE_APPEND//在尾部添加数据(不会覆盖前面的数据)
Context.MODE_PRIVATE//每次打开都先覆盖之前的数据
不需要特意创建文件,在文件打开时,如果没有,会自动创建的。
连接上手机之后,我们就可以看到文件在哪了。
在右下角点击:
弹出这么个界面
然后打开data,再打开data
找到对应的包名
点开files,就看到对应的文件了
打开一个文件
2.权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.listadapter">
<!-- 获取读写权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<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/Theme.ListAdapter"
tools:ignore="AllowBackup">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
这样就可以了。