运行截图

activity_main.xml(约束布局)

<?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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="76dp"
android:onClick="btnRead"
android:text="btnRead"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="68dp"
android:onClick="btnWrite"
android:text="btnWrite"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package cn.lwx.readwritetemplate;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnRead(View view) {
FileInputStream fileInputStream = null;
try {
// 1.打开文件
fileInputStream = openFileInput("aaa.txt");
// 2.读操作 字节流(byte 10001) -----> 字符流(编码)ASCLL 流操作
// Stream 字节流,reader write字符流
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = null;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println(builder.toString());
// String str = new String();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 3.关闭文件
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void btnWrite(View view) {
FileOutputStream fileOutputStream = null;
try {
// 1.打开文件
fileOutputStream = openFileOutput("aaa.txt", MODE_PRIVATE);
// 2.写操作
fileOutputStream.write("卫星同学,好帅啊~ 我也要嫁给他~~~".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
网友评论