简单的文件读写
1、布局文件(activity_main.xml)中添加一个Edit Text
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/edit_text" android:text="Type Something "/> </LinearLayout>
2、主MainActivity中保存数据方法save、读取数据方法load
package com.example.filesavetest; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.edit_text); String inputText = load(); if(!TextUtils.isEmpty(inputText)){ editText.setText(inputText); editText.setSelection(inputText.length()); Toast.makeText(MainActivity.this, "Restore succeed", Toast.LENGTH_SHORT).show(); } } @Override protected void onDestroy() { super.onDestroy(); String inputText = editText.getText().toString(); save(inputText); } public void save(String data) { FileOutputStream out = null; BufferedWriter writer = null; try { out = openFileOutput("data", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(data); } catch (Exception e) { e.printStackTrace(); }finally { if(null != writer){ try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String load(){ FileInputStream in = null; BufferedReader reader = null; StringBuilder content = new StringBuilder(); try{ in = openFileInput("data"); reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while (null!= (line = reader.readLine())){ content.append(line); } } catch (Exception e){ e.printStackTrace(); }finally { if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return content.toString(); } }
3、在模拟器或Android手机中运行即可