1.数据持久化-SDCard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//数据持久化-SDCard
findViewById(R.id.button1).setOnClickListener(
new
OnClickListener()
{
@Override
public
void
onClick(View v)
{
//判断SDCard是否正常加载
if
(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
//获取SDCard根目录
File sdcardPath = Environment.getExternalStorageDirectory();
//获取SDCard可用空间
long
freeSpace = sdcardPath.getFreeSpace();
Log.e(
"space"
, freeSpace +
""
);
}
}
});
|
2.SharedPreferences:(data/data/包名/shared_prefs/)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
private
void
btn2Click()
{
// SharedPreferences sp = getPreferences(0);
SharedPreferences sp = getSharedPreferences(
"filename"
, MODE_PRIVATE);
//私有模式
String str = sp.getString(
"value"
,
"noread"
);
boolean
bol = sp.getBoolean(
"flag"
,
true
);
textView.setText(str +
" "
+ bol);
}
private
void
btn1Click()
{
// SharedPreferences sp = getPreferences(MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);//全局可读可写
SharedPreferences sp = getSharedPreferences(
"filename"
, MODE_APPEND);
//指定文件名,(内容)追加模式
Editor editor = sp.edit();
String value = editText.getText().toString();
editor.putString(
"value"
, value);
editor.putBoolean(
"flag"
,
false
);
editor.commit();
}
|
3.内部存储internalStorage:(data/data/包名/files/)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
private
void
btn2Click()
{
try
{
FileInputStream fis = openFileInput(
"fos1.txt"
);
//读取文件
int
length =
0
;
byte
[] buffer =
new
byte
[
1024
];
while
(-
1
!= (length = fis.read(buffer)))
{
textView.setText(
new
String (buffer,
0
,length));
}
}
catch
(FileNotFoundException e)
{
e.printStackTrace();
}
catch
(IOException e)
{
e.printStackTrace();
}
}
private
void
btn1Click()
{
FileOutputStream fos =
null
;
try
{
fos = openFileOutput(
"fos1.txt"
,MODE_PRIVATE);
//写入文件
String str = editText.getText().toString();
fos.write(str.getBytes());
fos.flush();
}
catch
(FileNotFoundException e)
{
e.printStackTrace();
}
catch
(IOException e)
{
e.printStackTrace();
}
finally
{
if
(
null
!= fos )
{
try
{
fos.close();
}
catch
(IOException e)
{
e.printStackTrace();
}
}
}
}
|
本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1215469,如需转载请自行联系原作者