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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
package
tools;
import
java.io.ByteArrayOutputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.InputStream;
import
java.util.Date;
import
android.annotation.SuppressLint;
import
android.content.Context;
import
android.content.SharedPreferences;
public
class
ReadContentFile {
/**
* 打开sdcard的txt文件
*
* @param fileName
* @return
*/
@SuppressLint
(
"SdCardPath"
)
public
String getContentFromSDcardFile(String fileName) {
String content =
null
;
try
{
File fl =
new
File(
"/sdcard/"
+ fileName);
// 找到对应的文件路径
int
length = (
int
) fl.length();
byte
[] buff =
new
byte
[length];
FileInputStream fs =
new
FileInputStream(fl);
fs.read(buff);
// 从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中
fs.close();
// 关闭此输入流并释放与此流关联的所有系统资源
content =
new
String(buff,
"UTF-8"
);
}
catch
(Exception e) {
// TODO: handle exception
}
return
content;
}
/**
* 从assert中读取数据
*
* @param context
* @param fileName
* @return
*/
public
String loadFromAssert(Context context, String fileName) {
String content =
null
;
// 结果字符串
try
{
InputStream is = context.getResources().getAssets().open(fileName);
// 打开文件
int
ch =
0
;
ByteArrayOutputStream baos =
new
ByteArrayOutputStream();
// 实现了一个输出流
while
((ch = is.read()) != -
1
) {
baos.write(ch);
// 将指定的字节写入此 byte 数组输出流。
}
byte
[] buff = baos.toByteArray();
// 以 byte 数组的形式返回此输出流的当前内容
baos.close();
// 关闭流
is.close();
// 关闭流
content =
new
String(buff,
"UTF-8"
);
// 设置字符串编码
}
catch
(Exception e) {
// Toast.makeText(this, "对不起,没有找到指定文件!", Toast.LENGTH_SHORT).show();
}
return
content;
}
/**
* 从/preference中读取数据
*
* @param context
* @param keyName
* @return
*/
public
String laodFromPreference(Context context, String keyName) {
String content =
null
;
SharedPreferences sp = context.getSharedPreferences(
"sharePre"
,
Context.MODE_PRIVATE);
// 返回一个SharedPreferences实例,第一个参数是Preferences名字,第二个参数是使用默认的操作
String lastLogin = sp.getString(
// 从SharedPreferences中读取上次访问的时间
keyName,
// 键值
null
// 默认值
);
if
(lastLogin ==
null
) {
lastLogin =
"欢迎您,您是第一次访问本Preferences"
;
}
else
{
lastLogin =
"欢迎回来,您上次于"
+ lastLogin +
"登录"
;
}
// 向SharedPreferences中写回本次访问时间
SharedPreferences.Editor editor = sp.edit();
String keyValue =
new
Date().toString();
// 当前时间
editor.putString(keyName, keyValue);
// 向editor中放入键值
editor.commit();
// 提交editor
content = lastLogin;
return
content;
}
}
|