当前位置: 首页 > 编程日记 > 正文

Android 数据存储-内外部存储测试

案例分析:FilePersistenceTest

在EditText中输入文本内容,退出应用程序或者 单击“保存”按钮时

保存EditText中的数据到名 为“data”的文件中。

打开Device File Explorer,该文件应该存于 /data/data/cn.edu.hunnu.filepersistencetest/files/ 目录

MainActivity.java

package cn.edu.hunnu.filepersisttest;import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
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 edit;private Button bt_save_in;private Button bt_read_in;private Button bt_save_out;private Button bt_read_out;private Button bt_clr_edit;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);edit = (EditText)findViewById(R.id.edit);bt_clr_edit = (Button)findViewById(R.id.bt_clr_edit);bt_clr_edit.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {edit.setText("");}});bt_save_in = (Button)findViewById(R.id.bt_save_in);bt_save_in.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = edit.getText().toString();saveToInternalStorage(inputText);Toast.makeText(MainActivity.this,"Save to internal storage succeeded",Toast.LENGTH_SHORT).show();}});bt_read_in =(Button)findViewById(R.id.bt_read_in);bt_read_in.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = loadFromInternalStorage();if (!TextUtils.isEmpty(inputText)) {edit.setText(inputText);edit.setSelection(inputText.length());Toast.makeText(MainActivity.this, "Restoring from internal storage succeeded", Toast.LENGTH_SHORT).show();}}});bt_save_out = (Button)findViewById(R.id.bt_save_out);bt_save_out.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = edit.getText().toString();saveToExternalStorage(inputText);Toast.makeText(MainActivity.this,"Save to external storage succeeded",Toast.LENGTH_SHORT).show();}});bt_read_out = (Button)findViewById(R.id.bt_read_out);bt_read_out.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = loadFromExternalStorage();if (!TextUtils.isEmpty(inputText)) {edit.setText(inputText);edit.setSelection(inputText.length());Toast.makeText(MainActivity.this, "Restoring from external storage succeeded", Toast.LENGTH_SHORT).show();}}});}public void saveToInternalStorage(String inputText) {FileOutputStream out = null;BufferedWriter writer = null;try {out = openFileOutput("data", Context.MODE_PRIVATE);writer = new BufferedWriter(new OutputStreamWriter(out));writer.write(inputText);} catch (IOException e) {e.printStackTrace();} finally {try {if (writer != null) {writer.close();}} catch (IOException e) {e.printStackTrace();}}}public String loadFromInternalStorage() {FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput("data");reader = new BufferedReader(new InputStreamReader(in));String line = "";while ((line = reader.readLine()) != null) {content.append(line);}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();}public void saveToExternalStorage(String inputText) {String environment = Environment.getExternalStorageState();if(Environment.MEDIA_MOUNTED.equals(environment)) {//外部设备可以进行读写操作//保存在外部存储根目录,卸载应用时不能删除该文件//File sd_path = Environment.getExternalStorageDirectory();
//            Log.e("MainActivity",sd_path.toString());
//            File file = new File(sd_path,"test.txt");//保存在外部私有目录,卸载时会同时删除该文件String sd_path = this.getExternalFilesDir("").getAbsolutePath();Log.e("MainActivity+",sd_path);File file = new File(sd_path);if(!file.exists()){//判断文件目录是否存在file.mkdirs();}file = new File(sd_path,"text.txt");FileOutputStream fos;try{//写入数据fos = new FileOutputStream(file);OutputStreamWriter  osw = new OutputStreamWriter(fos);osw.write(inputText);osw.flush();osw.close();fos.close();}catch(Exception exception){exception.printStackTrace();}}}public String loadFromExternalStorage() {String content = null;String environment = Environment.getExternalStorageState();if(Environment.MEDIA_MOUNTED.equals(environment)) {
//            File sd_path = Environment.getExternalStorageDirectory();
//            Log.e("MainActivity",sd_path.toString());
//            File file = new File(sd_path,"test.txt");String sd_path = this.getExternalFilesDir("").getAbsolutePath();File file = new File(sd_path,"text.txt");Log.e("MainActivity+",file.getPath());FileInputStream fis;try{//读取文件fis = new FileInputStream(file);InputStreamReader  isr = new InputStreamReader(fis,"UTF-8");char[] input = new char[fis.available()];isr.read(input);content = new String(input);isr.close();fis.close();}catch(Exception exception){exception.printStackTrace();}}return content;}@Overrideprotected void onDestroy() {super.onDestroy();String inputText = edit.getText().toString();saveToInternalStorage(inputText);Toast.makeText(MainActivity.this,"Save to internal storage succeeded",Toast.LENGTH_SHORT).show();}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"android:padding="5dp"android:orientation="vertical"tools:context=".MainActivity"><EditTextandroid:id="@+id/edit"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10"android:hint="Type something here" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/bt_save_in"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="保存(内部存储)" /><Buttonandroid:id="@+id/bt_read_in"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="读取(内部存储)" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/bt_save_out"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="保存(外部存储)" /><Buttonandroid:id="@+id/bt_read_out"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="读取(外部存储)" /></LinearLayout><Buttonandroid:id="@+id/bt_clr_edit"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="清空输入框" /></LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.filepersisttest"><uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name = "android.permission. READ_EXTERNAL_STORAGE"/><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

相关文章:

微软以后要是也开源也免费,java还竞争过.NET吗?

上次参加招聘会&#xff0c;看得到好多大公司都要求精通java&#xff0c;可惜上大学大一就学了.NET,而java到大三才开&#xff0c;并且草草地只讲了些基本知识。有时我就在想难道学当初选择.NET真的错了吗&#xff1f;java确实比.NET存在很多优势。开源、跨平台、免费、开发工具…

Android Studio开发环境及第一个项目

1. 在你的电脑上搭建Android平台开发环境。 2. 新建项目&#xff0c;实现以下基本内容&#xff1a; (1) 修改默认的APP的名称和图标&#xff08;任意的&#xff0c;非默认的&#xff09;。 (2) 显示个人信息&#xff0c;包括&#xff1a;照片、专业、姓名、学号等基本信息。…

去除inline-block元素间距

转载于:https://www.cnblogs.com/keepitreal/p/10301199.html

C#ListView控件添加Checkbox复选框并获取选中的数目,检查checkbox是否勾选

[转载]原地址&#xff1a;http://blog.csdn.net/lucky51222/article/details/41892429 具体方法 1、添加复选框 并且如下设置 listView1.CheckBoxes true; 2、选中listview并获取选中的数目&#xff1a; 具体代码 private void listView1_ItemChecked(object sender, ItemChec…

weblogic学习笔记(1)

weblogic安装、配置和启动 1、weblogic安装转载于:https://blog.51cto.com/pengchenga/66424

react 从使用 看定义

如果你创建了一个类似元素做出反应Twitter的下面&#xff0c;你会的组件定义Twitter的样子&#xff1f; <Twitter usernametylermcginnis33>{(user) > user null? <Loading />: <Badge info{user} />} </Twitter> import React, { Component, Pro…

Android 活动与活动间数据传递

实验内容 综合运用基本组件完成一个注册与登录的应用程序设计。要求基于基础控件&#xff0c;综合使用Intent实现Android的Activity之间信息交换。系统包含启动页、注册页、登录页3个页面&#xff0c;具体要求如下&#xff1a; 1.注册页面和功能的实现。 –界面要求包含用户…

Selenium-js弹窗浮层

学习过js的小伙伴会发现&#xff0c;我们在一些实例中用到了alert()方法、prompt()方法、prompt()方法&#xff0c;他们都是在屏幕上弹出一个对话框&#xff0c;并且在上面显示括号内的内容&#xff0c;使用这种方法使得页面的交互性更精彩&#xff0c;实际上我们经常会在进行网…

JAVA基础(JAVA 执行环境) 第一天

JAVA程序有3中执行环境。 &#xff08;1&#xff09;能够单独运行的程序&#xff0c;称为Java Application(Java应用程序)。 &#xff08;2&#xff09;在Internet浏览器中运行的程序&#xff0c;称为 Java Applet&#xff08;JAVA小用用程序&#xff09;。Applet是一个在WEB浏…

ERP图形目录

这些天正在研究ERP&#xff0c;老师要求我们自己制作一个ERP出来。找了不少资料&#xff0c;就这个图形目录比较有学习价值。这个图形目录是PDF文件&#xff0c;包括销售管理、采购管理、库存管理、制作标准管理、计划管理、车间管理、JIT生产管理、质量管理、财务管理、人力资…

JSP学习笔记(五):日期处理、页面重定向、点击量统计、自动刷新和发送邮件...

一、JSP 日期处理&#xff1a; 使用JSP最重要的优势之一&#xff0c;就是可以使用所有Java API。本节讲述Java中的Date类&#xff0c;它在java.util包下&#xff0c;封装了当前日期和时间。 Date类有两个构造函数。第一个构造函数使用当前日期和时间来初始化对象&#xff1a;D…

完善登录注册页面

实验内容 综合运用基本组件完成一个注册与登录的应用程序设计。要求基于基础控件&#xff0c;综合使用Intent实现Android的Activity之间信息交换。系统包含启动页、注册页、登录页3个页面&#xff0c;具体要求如下&#xff1a; 在第2周上机作业的基础上&#xff0c;完善登录注…

EF 批量 添加 修改 删除

1批量添加 db.T_Investigator.AddRange(list) 2批量删除 db.T_Investigator.RemoveRange(list) 3批量修改 for 循环修改。 注意&#xff1a; 先查询出来&#xff0c;最后savechange&#xff08;&#xff09;&#xff0c;写在一个事务中&#xff0c;一次请求一个上下文。…

在IE7中无效的解决办法

通过ShowModalDialog 打开页面,在POSTBACK时,打开新的页面&#xff0c; 在IE6下没问题,只有在IE7下,会重新打开一新页面&#xff0c; 其实只要把<base target"_self"/> 放到 <head>下即可。 <head> <base target"_self"/> …

简单的纹理管理器

简单的纹理管理器 罗朝辉 (http://www.cnblogs.com/kesalin/)本文遵循“署名-非商业用途-保持一致”创作公用协议游戏中的资源一般都是由资源管理器来处理的&#xff0c;资源管理器负责载入&#xff0c;释放&#xff0c;以及根据资源ID返回相关资源供游戏程序使用。下面改写sph…

记住密码以及Android 列表的操作

1.综合使用RecycleView&#xff0c;CardView&#xff0c;Adapter实现一个宝宝相册&#xff0c;并将其加入到实验一形成的应用中&#xff0c;使得&#xff1a;用户成功登录后转到宝宝相册所在的主界面。还要求实现&#xff1a;用户单击对应的列表子项的不同部位时给出不同的Toas…

python-----利用filecmp删除重复文件

以下代码素材自取&#xff1a;链接&#xff1a;https://pan.baidu.com/s/1fL17RjKyGjpvpeeUFONCaQ 提取码&#xff1a;zgiw # coding:utf-8 import os import filecmp# 将指定目录下的所有文件的路径存储到all_files变量中 def get_all_files(path, dirs):all_files []for d …

如何设置REUSE_ALV_GRID_DISPLAY'的单个单元格的是否可以输入

代码如下&#xff1a;具体说明参见红色说明(本例子是从订单明细提取两个字段的数据到内表) REPORT ZALV_EDIT.TYPE-POOLS: SLIS.*- FieldcatalogDATA: IT_FIELDCAT TYPE LVC_T_FCAT.DATA: X_FIELDCAT TYPE LVC_S_FCAT.DATA: X_LAYOUT TYPE LVC_S_LAYO. "第1步&#xff1a;…

记一次生产的bug

第一个在代码中使用 new SimpleDateFormat("EEEE")来判断周几。在本地测试过程中通过日志打印出来的周几 比如周日对应的是中文汉字“星期日”&#xff0c;然后使用判断 if("星期日".equals(weekDay)){ } (其中weekDay是要使用的日期)。在本地测试通过后…

企业ERP制度的“执行力”

一直都很想说这个话题。可能很多人不是太理解这个标题&#xff0c;企业ERP制度是指完成了ERP系统实施的企业&#xff0c;为了维持ERP系统的持续运行而建立的ERP运行制度。执行力就不用多说了&#xff0c;就是ERP运行制度到底执行了多少&#xff0c;怎么执行的问题。许多管理软件…

python学习点滴记录-Day10-线程

多线程 协程 io模型 并发编程需要掌握的点&#xff1a; 1 生产者消费者模型2 进程池线程池3 回调函数4 GIL全局解释器锁 线程 理论部分 &#xff08;摘自egon老师博客&#xff09; 一、定义&#xff1a; 在传统操作系统中&#xff0c;每个进程有一个地址空间&#xff0c;而且默…

适配设备的简易新闻浏览器

同时兼容手机和平板。 进入应用后先显示新闻列表&#xff0c;当在手机上使用时&#xff0c;使用单页模式&#xff0c;单击列表项会打开新的页面。 当在平板上使用时&#xff0c;使用双页模式&#xff0c;单击左侧列表项时直接更新右侧新闻内容页。 MainActivity.java pack…

this.$router.push、replace、go的区别

1.this.$router.push() 描述&#xff1a;跳转到不同的url&#xff0c;但这个方法会向history栈添加一个记录&#xff0c;点击后退会返回到上一个页面。 用法&#xff1a; 2.this.$router.replace() 描述&#xff1a;同样是跳转到指定的url&#xff0c;但是这个方法不会向histor…

jQuery 实现图片的特效1[原]

用jQuery实现图片的动画效果非常简单.以下演示 jQuery里面所用到的参数 HIDE SHOW FADEOUT FADEIN 的不同. 在线演示:单击演示 代码分析: //hide and show fadeout and fadein $("input:eq(0)").click(function(){ $("img").fadeOut(3000); }); …

【设计模式】 模式PK:策略模式VS状态模式

1、概述 行为类设计模式中&#xff0c;状态模式和策略模式是亲兄弟&#xff0c;两者非常相似&#xff0c;我们先看看两者的通用类图&#xff0c;把两者放在一起比较一下。 策略模式&#xff08;左&#xff09;和状态模式&#xff08;右&#xff09;的通用类图。 两个类图非常相…

vs2008与IIS 7.0使用在vista上时出现的问题及解决方法(Internet Explorer 无法显示该页面)(VS2008: IE Cannot Display Web Page)...

我的系统是Vista Ultimate SP1,先安装了vs2008 ,然后再安装了IIS7.0之后就出现了一系列的问题。 问题&#xff1a;通过vs2008启动程序调试时报错。错误提示为&#xff1a;Internet Explorer 无法显示该页面 解决方法&#xff1a; 首先是安装一些必要的附件程序。 1.打开控制面板…

云服务中IaaS、PaaS、SaaS的区别

越来越多的软件&#xff0c;开始采用云服务。 云服务只是一个统称&#xff0c;可以分成三大类。 IaaS&#xff1a;基础设施服务&#xff0c;Infrastructure-as-a-servicePaaS&#xff1a;平台服务&#xff0c;Platform-as-a-serviceSaaS&#xff1a;软件服务&#xff0c;Softwa…

Android项目框架综合实例

综合使用ViewPager、Fragment、RecycleView等&#xff0c;实现类似“网易新闻浏览器 ”的项目综合框架&#xff0c;要求实现&#xff1a; 底部导航&#xff0c;分别是“首页”&#xff0c;“视频”&#xff0c;“讲讲”&#xff0c;“我的”&#xff1b;底部导航不要求滑动翻页…

配置Windows Server 2003 的RADIUS Server的方法

配置Windows Server 2003 的RADIUS Server的方法1、安装Windows 2003操作系统&#xff1b;2、添加角色&#xff08;须插网线&#xff09;&#xff1b;3、添加组件->网络服务、证书服务&#xff1b;4、管理工具->域安全策略->帐户策略->密码策略&#xff1b;&#x…

Y15BeTa蜂鸣器唱歌程序-演奏版

最优版&#xff0c;自由演奏你的音乐&#xff01; 每天进步一点点&#xff01; 2018-12-09最新版 #include<bits/stdc.h> #include<windows.h> using namespace std; int md[8]{0,262,294,330,349,392,440,494}, mz[8]{0,523,587,659,698,784,880,988}, mg[8]{0,10…