package com.example.qihao.myapplication; import android.app.Activity; import android.content.Context; 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.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends Activity { private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main); editText = (EditText) findViewById(R.id.edit); String loadString = load(); // TextUtils.isEmpty(loadString) 可以判断二种空值的判断。 // 当输入的字符串等于null,或者等于空字符的时候,都会返回true if (!TextUtils.isEmpty(loadString)) { editText.setText(loadString); editText.setSelection(loadString.length()); Toast.makeText(this, "Load success", Toast.LENGTH_LONG).show(); } } @Override protected void onDestroy() { super.onDestroy(); String inputText = editText.getText().toString(); save(inputText); } public void save(String inputText) { FileOutputStream out = null; BufferedWriter writer = null; try { // MODE_PRIVATE:覆盖原来的内容 // MODE_APPEND:在已存在的文件里添加 out = openFileOutput("qihao", Context.MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } } public String load() { FileInputStream in = null; BufferedReader reader = null; StringBuilder content = new StringBuilder(); try { in = openFileInput("qihao"); reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { content.append(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return content.toString(); } }
Android 文件存储
最新推荐文章于 2023-04-03 13:12:54 发布