Android下的数据存储与訪问 --- 以文件的形式

时间:2024-01-20 21:28:39
Android下的数据存储与訪问 --- 以文件的形式

	1.1 储存文件存放在手机内存中:

		// *** 储存数据到 /data/data/包名/files/jxn.txt文件里
String data = "test"; // /data/data/包名/files
File filesDir = context.getFilesDir(); File file = new File(filesDir, "jxn.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(data.getBytes());
fos.flush();
fos.close(); // *** 从 /data/data/包名/files/jxn.txt文件里读取数据
String data = "test";
File filesDir = context.getFilesDir();
File file = new File(filesDir, "jxn.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String text = reader.readLine();
reader.close(); 补充:
1,在Android上下文中openFileOutput()方法能够把数据写到/data/data/包名/files文件夹下
2。在Android上下文中openFileInput()方法能够读取/data/data/包名/files文件夹下的文件
3,详细的实现过程与在J2SE环境中保存数据到文件里是一样的。 eg:
// openFileOutput()方法的第一參数用于指定文件名,不能包括路径分隔符“/” ,假设文件不存在。Android会自己主动创建
// 存放路径:/data/data/包名/files/jxn.txt
FileOutputStream outStream = context.openFileOutput("jxn.txt", Context.MODE_PRIVATE); SharedPreferences
1,Android提供了一个SharedPreferences类。它是一个轻量级的存储类。特别适合用于保存软件配置參数。
2。使用SharedPreferences保存数据,其最后是用xml文件存放数据,文件存放在/data/data/包名/shared_prefs文件夹下
3,context.getSharedPreferences(name,mode)方法的第一个參数用于指定该文件的名称,名称不用带后缀,Android会自己主动地加上.xml后缀。 // *** 储存数据到 /data/data/包名/shared_prefs/jxn.xml文件里 // /data/data/包名/shared_prefs/jxn.xml
SharedPreferences sp = context.getSharedPreferences("jxn", Context.MODE_PRIVATE); // 获得一个Editor对象
Editor edit = sp.edit(); // 存数据
edit.putString("number", number);
edit.putString("password", password); // 提交, 数据就保存到文件里了
edit.commit(); // *** 从 /data/data/包名/shared_prefs/jxn.xml文件里读取数据 SharedPreferences sp = context.getSharedPreferences("jxn", Context.MODE_PRIVATE); String number = sp.getString("number", null);
String password = sp.getString("password", null); 1.2 储存文件存放在SD卡中: // *** 储存数据到 /mnt/sdcard/jxn.txt文件里 // 推断当前的手机是否有sd卡;假设有SD卡,而且能够读写。则方法返回Environment.MEDIA_MOUNTED
String state = Environment.getExternalStorageState();
if(!Environment.MEDIA_MOUNTED.equals(state)) {
return false;
} String data = "test"; // 一般为 /mnt/sdcard 可是不同手机的sd卡的文件夹可能不同
File sdCardFile = Environment.getExternalStorageDirectory(); File file = new File(sdCardFile, "jxn.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(data.getBytes());
fos.flush();
fos.close(); // *** 从 /mnt/sdcard/jxn.txt文件里读取数据 // 推断当前的手机是否有sd卡
String state = Environment.getExternalStorageState();
if(!Environment.MEDIA_MOUNTED.equals(state)) {
return null;
} File sdCardFile = Environment.getExternalStorageDirectory();
File file = new File(sdCardFile, "jxn.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String text = br.readLine();
br.close(); <!-- 设置写入和读取sd卡的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />