
课程咨询: 400-996-5531 / 投诉建议: 400-111-8989
认真做教育 专心促就业
1.向SharedPreferences 中存储字符串昆明IT培训首选达内
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
|
/**
* 缓存文本数据
*
* @param context
* @param key
* @param value
*/
public static void putString(Context context, String key, String value) {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
///mnt/sdcard/beijingnews/files/llkskljskljklsjklsllsl
try {
String fileName = MD5Encoder.encode(key);//llkskljskljklsjklsllsl
///mnt/sdcard/beijingnews/files/llkskljskljklsjklsllsl
File file = newFile(Environment.getExternalStorageDirectory() + "/beijingnews/files", fileName);
File parentFile = file.getParentFile();//mnt/sdcard/beijingnews/files
if (!parentFile.exists()) {
//创建目录
parentFile.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
//保存文本数据
FileOutputStream fileOutputStream = newFileOutputStream(file);
fileOutputStream.write(value.getBytes());
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
LogUtil.e("文本数据缓存失败");
}
} else {
SharedPreferences sp = context.getSharedPreferences("atguigu", Context.MODE_PRIVATE);
sp.edit().putString(key, value).commit();
}
}
|
2.从SharedPreferences 中获取存储的字符串
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
|
/**
* 获取缓存的文本信息
*
* @param context
* @param key
* @return
*/
public static String getString(Context context, String key) {
String result = "";
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
String fileName = MD5Encoder.encode(key);//llkskljskljklsjklsllsl
///mnt/sdcard/beijingnews/files/llkskljskljklsjklsllsl
File file = newFile(Environment.getExternalStorageDirectory() + "/beijingnews/files", fileName);
if (file.exists()) {
FileInputStream is =new FileInputStream(file);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] buffer = newbyte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
stream.write(buffer, 0, length);
}
is.close();
stream.close();
result = stream.toString();
}
} catch (Exception e) {
e.printStackTrace();
LogUtil.e("图片获取失败");
}
} else {
SharedPreferences sp = context.getSharedPreferences("atguigu", Context.MODE_PRIVATE);
result = sp.getString(key, "");
}
return result;
}
|