[Android新手学习笔记33]-Storage-文件存储

  
  
  1. public class MainActivity extends AppCompatActivity {
  2.    private EditText editText;
  3.    @Override
  4.    protected void onCreate(Bundle savedInstanceState) {
  5.        super.onCreate(savedInstanceState);
  6.        setContentView(R.layout.activity_main);
  7.        editText = (EditText) findViewById(R.id.edit_text);
  8.        String inputText = load();
  9.        if (!TextUtils.isEmpty(inputText)) {
  10.            editText.setText(inputText);
  11.            editText.setSelection(inputText.length());
  12.            Toast.makeText(this, "恢复成功", Toast.LENGTH_SHORT).show();
  13.        }
  14.    }
  15.    @Override
  16.    protected void onDestroy() {
  17.        super.onDestroy();
  18.        save(editText.getText().toString());
  19.    }
  20.    public void save(String inputText) {
  21.        FileOutputStream out = null;
  22.        BufferedWriter writer = null;
  23.        try {
  24.            out = openFileOutput("data", Context.MODE_PRIVATE);
  25.            writer = new BufferedWriter(new OutputStreamWriter(out));
  26.            writer.write(inputText);
  27.        } catch (FileNotFoundException e) {
  28.            e.printStackTrace();
  29.        } catch (IOException e) {
  30.            e.printStackTrace();
  31.        } finally {
  32.            try {
  33.                if (writer != null) {
  34.                    writer.close();
  35.                }
  36.            } catch (IOException e) {
  37.                e.printStackTrace();
  38.            }
  39.        }
  40.    }
  41.    public String load() {
  42.        FileInputStream in = null;
  43.        BufferedReader reader = null;
  44.        StringBuilder content = new StringBuilder();
  45.        try {
  46.            in = openFileInput("data");
  47.            reader = new BufferedReader(new InputStreamReader(in));
  48.            String line = "";
  49.            while ((line = reader.readLine()) != null) {
  50.                content.append(line);
  51.            }
  52.        } catch (FileNotFoundException e) {
  53.            e.printStackTrace();
  54.        } catch (IOException e) {
  55.            e.printStackTrace();
  56.        } finally {
  57.            if (reader != null) {
  58.                try {
  59.                    reader.close();
  60.                } catch (IOException e) {
  61.                    e.printStackTrace();
  62.                }
  63.            }
  64.        }
  65.        return content.toString();
  66.    }
  67. }

文件默认存储到/data/data/<packagename>/files/目录下。MODE_PRIVATE表示覆盖,MODE_APPEND表示追加。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值