布局文件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
写入数据到sd卡中:
- 创建一个File文件路径;
- 创建一个File文件;
- 向文件中写入数据;
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "data.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write("hello Geoff".getBytes("utf-8"));
fos.flush();
fos.close();
从文件中读取数据;
FileInputStream inputStream =new FileInputStream(file);
byte[]bytes =new byte[inputStream.available()];
inputStream.read(bytes);
给控件赋值
tv.setText(new String(bytes));
代码如下:
package com.example.sdsave;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=findViewById(R.id.tv);
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "data.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("hello Geoff".getBytes("utf-8"));
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileInputStream inputStream =new FileInputStream(file);
byte[]bytes =new byte[inputStream.available()];
inputStream.read(bytes);
tv.setText(new String(bytes));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最后记得在AndroidManifest.xml加入权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
这是向内存卡中写入权限和读取内存卡的权限;