吴小龙同學

Saving Data-Saving Files

微言App中有个阅读量的功能,是直接将用户的阅读量保存在SD卡上,我封装成了工具类。

效果预览

实例APK

需要权限

1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

ReadUtil.java

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
public class ReadUtil {
public static final File SDCardDir = Environment.getExternalStorageDirectory(); //获取SDCard目录
public static final String SD_ROOT_NAME = "WeiYan/";
public static final String SD_FILE_NAME = "reading";
public static void saveToFile(int readTotal) {
try {
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File saveFile = new File(SDCardDir + File.separator + SD_ROOT_NAME, SD_FILE_NAME);
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
int nowReadingTotal = getReadedTotal() + readTotal;
String readedTotal = nowReadingTotal + "";
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write(readedTotal.getBytes());
outStream.close();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getReadedTotal() {
int readedTotal = 0;
File file = new File(SDCardDir + File.separator + SD_ROOT_NAME, SD_FILE_NAME);
if (file.exists() && file.isFile()) {
StringBuffer stringBuffer = new StringBuffer();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
int c;
while ((c = bufferedReader.read()) != -1) {
stringBuffer.append((char) c);
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
String result = stringBuffer.toString();
readedTotal = Integer.parseInt(result);
}
return readedTotal;
}
}

如何调用

读取数据

1
ReadUtil.getReadedTotal()

保存阅读量

1
ReadUtil.saveToFile(readTotal);


联系我

我的微信公众号:吴小龙同学,欢迎关注交流~

剩者为王⑤群:590967484
剩者为王⑤群