package com.spx.docghifile;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
EditText ed_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_content = findViewById(R.id.ed_content);
}
public void SaveFile(View view){
String noidung = ed_content.getText().toString();
String file_name = "vidu.txt";
try {
// mở luồng tạo file
FileOutputStream fileOutputStream = openFileOutput(file_name, Context.MODE_PRIVATE);
// ghi dữ liệu vào file
fileOutputStream.write(noidung.getBytes());
// đóng luồng
fileOutputStream.close();
Toast.makeText(getBaseContext(),"Đã ghi vào file", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void ReadFile(View view){
String file_name = "vidu.txt";
//tạo đối tượng string buff để xây dựng chuỗi dữ liệu
StringBuffer stringBuffer = new StringBuffer();
try {
// luồng dữ liệu file
FileInputStream fileInputStream = openFileInput(file_name);
// khai báo luồng đọc dữ liệu
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
// tạo biến đệm cho quá trình đọc
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ( ( line = bufferedReader.readLine() ) != null ){
stringBuffer.append(line);
}
Toast.makeText(getBaseContext(), stringBuffer.toString(),Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
============ file layout ==============================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/ed_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nội dung bất kỳ"
/>
<Button
android:id="@+id/btn_save"
android:onClick="SaveFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save to file"/>
<Button
android:id="@+id/btn_read"
android:onClick="ReadFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read from file"/>
</LinearLayout>