Android 中 数据存储的基本使用
1. SharedPreferences
SharedPreferencesActivity 文件
package com.example.hello.dataStorage;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.hello.R;
public class SharedPreferencesActivity extends AppCompatActivity {
// 声明
private EditText etContent;
private TextView tvShowContent;
private Button btnSave, btnShow;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@SuppressLint("CommitPrefEdits")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_preferences);
sharedPreferences = getSharedPreferences("", MODE_PRIVATE);
editor = sharedPreferences.edit();
// 获取
etContent = findViewById(R.id.et_content);
tvShowContent = findViewById(R.id.tv_show_content);
btnSave = findViewById(R.id.btn_save);
btnShow = findViewById(R.id.btn_show);
// 点击事件
btnSave.setOnClickListener(v -> {
editor.putString("name", etContent.getText().toString());
// commit() 同步过程, apply() 异步过程.
editor.apply();
});
btnShow.setOnClickListener(v -> {
tvShowContent.setText(sharedPreferences.getString("name", ""));
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:padding="15dp"
tools:context=".dataStorage.SharedPreferencesActivity">
<EditText
android:id="@+id/et_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints=""
android:hint="@string/inputContent"
android:inputType="text" />
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/save"
android:textAllCaps="false" />
<Button
android:id="@+id/btn_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/show"
android:textAllCaps="false" />
<TextView
android:id="@+id/tv_show_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="@string/showContent"
android:gravity="center"/>
</LinearLayout>
2. File
Android 存储概念
2.1 内部存储
FileActivity 文件
package com.example.hello.dataStorage;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.hello.R;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileActivity extends AppCompatActivity {
// 声明
private EditText etContent;
private TextView tvShowContent;
private Button btnSave, btnShow;
private final static String FILE_NAME = "test.txt";
@SuppressLint("CommitPrefEdits")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
// 获取
etContent = findViewById(R.id.et_content);
tvShowContent = findViewById(R.id.tv_show_content);
btnSave = findViewById(R.id.btn_save);
btnShow = findViewById(R.id.btn_show);
// 点击事件
btnSave.setOnClickListener(v -> {
// .trim() 去除前后空格
save(etContent.getText().toString().trim());
});
btnShow.setOnClickListener(v -> {
tvShowContent.setText(read());
});
}
/**
* 存储数据
*
* @param content 存储内容
*/
private void save(String content) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = openFileOutput(FILE_NAME, MODE_PRIVATE);
fileOutputStream.write(content.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 读取数据
*
* @return 读取的内容
*/
private String read() {
FileInputStream fileIutputStream = null;
try {
fileIutputStream = openFileInput(FILE_NAME);
byte[] bytes = new byte[1024];
StringBuilder buffer = new StringBuilder();
int len = 0;
if ((len = fileIutputStream.read(bytes)) > 0) {
buffer.append(new String(bytes, 0, len));
}
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileIutputStream != null) {
try {
fileIutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
activity_file 文件和 activity_shared_preferences 内容是一样的.
2.2 外部存储
外部存储路径的设置
File path= getExternalFilesDir(type);
type 可以为:
1. null // 根目录
2. Environment.DIRECTORY_MUSIC //创建一个 music 目录
3. Environment.DIRECTORY_PODCASTS //创建一个 podcasts 目录
4. Environment.DIRECTORY_RINGTONES //创建一个 ringtones 目录
5. Environment.DIRECTORY_ALARMS //创建一个 alarms 目录
6. Environment.DIRECTORY_NOTIFICATIONS //创建一个 notifications 目录
7. Environment.DIRECTORY_PICTURES //创建一个 pictures 目录
8. Environment#DIRECTORY_MOVIES //创建一个 movies 目录
package com.example.hello.dataStorage;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.hello.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileActivity extends AppCompatActivity {
// 声明
private EditText etContent;
private TextView tvShowContent;
private Button btnSave, btnShow;
private final static String FILE_NAME = "test.txt";
@SuppressLint("CommitPrefEdits")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
// 获取
etContent = findViewById(R.id.et_content);
tvShowContent = findViewById(R.id.tv_show_content);
btnSave = findViewById(R.id.btn_save);
btnShow = findViewById(R.id.btn_show);
// 点击事件
btnSave.setOnClickListener(v -> {
// .trim() 去除前后空格
save(etContent.getText().toString().trim());
});
btnShow.setOnClickListener(v -> {
tvShowContent.setText(read());
});
}
/**
* 存储数据
*
* @param content 存储内容
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
private void save(String content) {
FileOutputStream fileOutputStream = null;
try {
// fileOutputStream = openFileOutput(FILE_NAME, MODE_PRIVATE);
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 读取数据
*
* @return 读取的内容
*/
private String read() {
FileInputStream fileInputStream = null;
try {
// fileInputStream = openFileInput(FILE_NAME);
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), FILE_NAME);
fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
StringBuilder buffer = new StringBuilder();
int len = 0;
if ((len = fileInputStream.read(bytes)) > 0) {
buffer.append(new String(bytes, 0, len));
}
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
开启权限
AndroidManifest.xml 文件内设置.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:requestLegacyExternalStorage="true" />
可以在 MainActivity 文件内设置.
// 申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);