跟我学Android之十二 文件解析与处理
本章内容
第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();
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();
浙公网安备 33010602011771号