本章内容
第1节 File Explorer操作
第2节 SharedPreferences
第3节 普通文件操作
第4节 SD卡读写操作
本章目标
熟练掌握FileExplorer的用法熟练掌握SharedPreference文件操作。熟练掌握普通文件的读写操作。熟练掌握SD卡读写操作的方法。
FileExplorer操作
查看文件结构创建文件夹导入文件导出文件及文件夹删除文件
SharedPreferences概述
首先通过Context. getSharedPreferences方法获得对象第一个参数是文件名,需要包含后缀名(自动设置为xml)第二个参数是访问模式,和普通文件的访问模式相同通过SharedPreferences中的方法读取数据
SharedPreferences sp = getSharedPreferences("config",
Context.MODE_PRIVATE);
Stringusername = sp.getString(“username”,“root”);
Stringpassword = sp.getString(“password”,“123456”);
首先通过Context. getSharedPreferences方法获得对象获取对象时采用写模式打开通过SharedPreferences获得Editor对象Editor对象中包含了写数据的方法数据写入完成后一定要执行commit方法让数据生效
SharedPreferences sp = getSharedPreferences("config",
Context.MODE_PRIVATE);
Editor editor =sp.edit();
editor.put(“username”, “root”);
editor.put(“password”, “123456”);
editor.commit();
pe:solid;mso-style-textfill-fill-themecolor:text1;mso-style-textfill-fill-color:black;mso-style-textfill-fill-alpha:100.0%'>方法让数据生效
外部访问SharedPreferences
Contextcontext = createPackageContext(PKGNAME,
CONTEXT_IGNORE_SECURITY);
SharedPreferences cfg = context.getSharedPreferences(
PREFERENCE_NAME, MODE);
利用openFileInput读取文件
FileInputStream inputStream = this.openFileInput(fileName);
byte[]bytes = new byte[1024];
ByteArrayOutputStream os= new ByteArrayOutputStream();
while(inputStream.read(bytes)!= -1) {
os.write(bytes, 0, bytes.length);
}
inputStream.close();
os.close();
Stringcontent = new String(os.toByteArray());
showTextView.setText(content);
FileOutputStream outputStream = openFileOutput(fileName,
Activity.MODE_PRIVATE);
outputStream.write(content.getBytes());
outputStream.flush();
outputStream.close();
mso-color-index:1;mso-font-kerning:12.0pt;language:zh-CN;mso-style-textfill-type:solid;mso-style-textfill-fill-themecolor:text1;mso-style-textfill-fill-color:black;mso-style-textfill-fill-alpha:100.0%'>公用模式下操作文件很危险,因为一旦并发将会带来程序的漏洞
Filedir = new File(“/mnt/sdcard”);
String[]s = dir.list();
FileInputStream in = new FileInputStream(“/mnt/sdcard/……”);
byte[] bytes = new byte[1024];
ByteArrayOutputStream os= new ByteArrayOutputStream();
while (in.read(bytes) != -1) {
os.write(bytes, 0, bytes.length);
}
in.close();
os.close();
String content = new String(os.toByteArray());
showTextView.setText(content);
FileOutputStream out = new FileOutputStream(“/mnt/sdcard/..”);
out.write(content.getBytes());
out.flush();
out.close();