Android App data write as file data with synchronous Demo
package com.android.utils; import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays; import android.app.Activity;
import android.util.Log; /**
* 在一些对数据实时性要求比较高的场合,如随时可能断电的场合下,同时需要将数据写入文件中,
* 这个时候,我们不希望数据在内存中呆太久,最好能够做到同步,这是我们的需求。<br>
* 第一种方案:<br>
* 1. RandomAccessFile<br>
* 2. public RandomAccessFile(File file, String mode) throws FileNotFoundException<br>
* Constructs a new RandomAccessFile based on file and opens it according to the access string in mode. <br>
* 3. mode may have one of following values: <br>
* 1. "r" The file is opened in read-only mode. An IOException is thrown if any of the write methods is called. <br>
* 2. "rw" The file is opened for reading and writing. If the file does not exist, it will be created. <br>
* 3. "rws" The file is opened for reading and writing. Every change of the file's content or metadata must be written synchronously to the target device. <br>
* 4. "rwd" The file is opened for reading and writing. Every change of the file's content must be written synchronously to the target device. <br>
* 4. 由于我们需要其中的数据同步功能,所以我们选择使用包装RandomAccessFile类,实现要求。<br>
* 第二种方案:<br>
* 1. FileDescriptor中有sync()方法<br>
Ensures that data which is buffered within the underlying implementation is written out to the appropriate device before returning.<br>
* 2. FileOutputStream中的 getFD()方法<br>
Returns a FileDescriptor which represents the lowest level representation of an operating system stream resource. <br>
* 3. 使用起来感觉没有RandomAccessFile方便,放弃时使用<br>
*/ public class ZengjfRandomAccessFile {
/**
* 将整形数组写入文件
*
* @param filePath 文件路径
* @param data 整形数组
* @throws IOException
*/
static public void writeIntArray(String filePath, int[] data) throws IOException {
if (null == filePath || null == data)
return ; if (filePath.trim().equals(""))
return ; File file = new File(filePath);
if (!file.exists())
file.createNewFile(); if (!file.canWrite())
throw new RuntimeException("Zengjf Utils writeIntArray(): no permission for file -- " + filePath + "."); // write data
RandomAccessFile raf = new RandomAccessFile(file, "rws");
for (int i = 0; i < data.length; i++)
raf.writeInt(data[i]); raf.close();
} /**
* 将整形数组写入文件,文件目录被指定,作为使用者可以不用关心
*
* @param activity 调用这个函数的Activity
* @param data 要保存的的整形数组
* @throws IOException
*/
static public void writeIntArray(Activity activity, int[] data) throws IOException {
if (null == activity || null == data)
return ; String filePath = activity.getApplicationContext().getFilesDir().getAbsoluteFile() + "/zengjfData.txt";
writeIntArray(filePath, data);
} /**
* 从文件中读出长度为length的整形数组
*
* @param filePath 文件路径
* @param length 数组长度
* @return 返回数组,如果出错,返回null
* @throws IOException
*/
static public int[] readIntArray(String filePath, int length) throws IOException { if (null == filePath || length <= 0)
return null; if (filePath.trim().equals(""))
return null; File file = new File(filePath);
if (!file.canRead())
throw new RuntimeException("Zengjf Utils writeIntArray(): no permission for file -- " + filePath + "."); int[] data = new int[length]; // for return data // if file not exist in first time and file length less than data size,
// just create file and make data for it
if (!file.exists() || (file.length() < (4 * length))) {
for (int i = 0; i < data.length; i++)
data[i] = 0; writeIntArray(filePath, data);
return data;
} //get data
RandomAccessFile raf = new RandomAccessFile(file, "r");
for (int i = 0; i < length; i++)
data[i] = raf.readInt(); raf.close(); return data;
} /**
* 从文件中读取整形数组,文件位置、名已经被指定,作为使用者可以不关心
*
* @param activity 调用这个函数的Activity
* @param length 数组的长度
* @return 返回数组,如果出错,返回null
* @throws IOException
*/
static public int[] readIntArray(Activity activity, int length) throws IOException {
if (null == activity || 0 == length)
return null; String filePath = activity.getApplicationContext().getFilesDir().getAbsoluteFile() + "/zengjfData.txt";
return readIntArray(filePath, length);
} /**
* 往文件中写入原始整形数组,其实就是填充整形0
*
* @param filePath 文件路径
* @param length 数组大小
* @throws IOException
*/
static public void writeRawIntArray(String filePath, int length) throws IOException { if (null == filePath || length <= 0)
return ; if (filePath.trim().equals(""))
return ; File file = new File(filePath);
int[] data = new int[length]; // for return data // if file not exist in first time, just create file and make data for it
if (file.exists()) {
for (int i = 0; i < data.length; i++)
data[i] = 0; writeIntArray(filePath, data);
}
} /**
*
* 往文件中写入值为0的整形数组,文件位置、名已经被指定,作为使用者可以不关心
*
* @param activity 调用这个函数的Activity
* @param length 写入数组的长度
* @throws IOException
*/
static public void writeRawIntArray(Activity activity, int length) throws IOException{
if (null == activity || 0 == length)
return ; String filePath = activity.getApplicationContext().getFilesDir().getAbsoluteFile() + "/zengjfData.txt";
writeRawIntArray(filePath, length);
} /**
* 测试用的的Demo
* @param activity 调用这个函数的Activity
*/
static public void testDemo(Activity activity) {
int[] data = {1, 2, 3, 4, 5, 6};
try {
writeIntArray(activity, data);
int[] redata = readIntArray(activity, 6);
Log.e("zengjf utils", Arrays.toString(redata));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Android App data write as file data with synchronous Demo的更多相关文章
- 07-09 07:28:38.350: E/AndroidRuntime(1437): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.googleplay.ui.activity.MainActivity" on path: DexPathList[[zip file "/data/app/c
一运行,加载mainActivity就报错 布局文件乱写一通,然后急着运行,报莫名其妙的错误: 07-09 07:28:38.350: E/AndroidRuntime(1437): Caused b ...
- Android错误:can not get file data of lua/start_v2.op [LUA ERROR] [string "require "lua/start_v2””] 已解决
错误: can not get file data of lua/start_v2.op [LUA ERROR] [string "require "lua/start_v2””] ...
- [转]在eclipse打开的android虚拟手机,打开File Explorer,下面是空的没有data、mnt、system三个文件
在eclipse打开的android虚拟手机,打开File Explorer,下面是空的没有data.mnt.system三个文件 这是因为模拟器没有选择打开的缘故,必须首先打开一个模拟器(AVD), ...
- Caused by: java.lang.ClassNotFoundException: Didn't find class "** *** ** **" on path: DexPathList[[zip file "/data/app/*** *** ***-2/base.apk"],nativeLibraryDirectories
Caused by: java.lang.ClassNotFoundException: Didn't find class "** *** ** **" on path: Dex ...
- Android 程序drawable资源保存到data目录
今天做了个小功能,就是把我们程序Drawable里面的图片保存到data目录下面,然后另外一个程序需要读取data目录里面保存的图片.涉及了data目录读写.这功能看上去挺简单,不过实际做的时候还是遇 ...
- android:Intent匹配action,category和data原则
1.当你在androidmanifest里面定义了一个或多个action时 你使用隐式意图其他activity或者service时,规定你隐式里面的action必须匹配XML中定义的action,可以 ...
- rac的一次问题 ORA-01565: error in identifying file '+DATA/bol/spfilebol.ora'
昨天安装的测试环境的rac--2节点 CentOS release 6.8 (Final) SQL*Plus: Release 11.2.0.4.0 Production 今天测试突然出现问题 在ra ...
- ORA-01578: ORACLE data block corrupted (file # 3, block # 1675)
警告日志中发现如下报错信息: ORA-01578: ORACLE data block corrupted (file # 3, block # 1675)ORA-01110: data file 3 ...
- couldn't open file: data/coco.names
在ubuntu下配置yolo(v2)的时候,编译了源码后,尝试运行demo: ./darknet detect cfg/yolo.cfg yolo.weights data/dog.jpg 结果报错提 ...
随机推荐
- 卡内基梅隆大学软件工程研究所先后制定用于评价软件系统成熟度的模型CMM和CMMI
SEI(美国卡内基梅隆大学软件工程研究所(Software Engineering Institute, SEI))开发的CMM模型有: 用于软件的(SW-CMM;SW代表'software即软件') ...
- Beta冲刺
第一天 日期:2018/6/24 1 今日完成任务情况. 妥志福.牛瑞鑫: 完成任务:数据库设计完成数据导入成功 王胜海.马中林: 完成任务:代码规范检查 董润园.邓英蓉: 完成任务:平台基本功能黑盒 ...
- windows 2012 R2安装SqlServer2016提示缺少KB2919355
补丁的安装顺序如下: 1, 首先安装 Windows2012R2更新的先决条件KB2919442.2,按照如下顺序安装后续KB文件.顺序:clearcompressionflag.exe.KB2919 ...
- MySQL修改时间函数 1.addDate(date , INTERVAL expr unit) 2.date_format(date,’%Y-%m-%d’) 3.str_to_date(date,’%Y-%m-%d’) 4.DATE_SUB(NOW(), INTERVAL 48 HOUR)
MySQL修改时间函数: 1. addDate(date,INTERVAL expr unit) interval 代表时间间隔 : SELECT NOW(); 2018-06 ...
- 新的请求方式 fetch和axios
参考链接:https://www.javascriptcn.com/read-5840.html axios使用文档: https://www.kancloud.cn/yunye/axios/2348 ...
- PHP求并集,交集,差集
PHP求并集,交集,差集 一.总结 一句话总结:在php中如果我想要对两个数组进行如并集.交集和差集操作,我们可直接使用php自带的函数来操作如array_merge(),array_intersec ...
- python-GUI,生成ssn
第一次做这个, 样子有点丑,主要是实现功能,做测试的时候,经常要用到身份证号.手机号.姓名等,这里先生成ssn,后续研究怎么做成客户端 代码: from tkinter import * from u ...
- English trip -- VC(情景课)5 Around Town
Around Town 城市周围 Talk about the picture 看图说话 sentences Where are you? I'm in the Meten classroom. ...
- 关于"架构"
杨光辉说,在构架系统的早期可能不会更多地考虑架构,主要是在做技术选型,首先是编程语言的选择.对于编程语言选择,当前主流编程语言有很多,有面向对象语言.传统式语言等.做这个选择主要根据人员知识储备,包括 ...
- UVA-10020 Minimal coverage(贪心)
题目大意:在x轴上,给一些区间,求出能把[0,m]完全覆盖的最少区间个数及该情形下的各个区间. 题目分析:简单的区间覆盖问题.可以按这样一种策略进行下去:在所有区间起点.长度有序的前提下,对于当前起点 ...