1. package com.android.utils;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.RandomAccessFile;
  6. import java.util.Arrays;
  7.  
  8. import android.app.Activity;
  9. import android.util.Log;
  10.  
  11. /**
  12. * 在一些对数据实时性要求比较高的场合,如随时可能断电的场合下,同时需要将数据写入文件中,
  13. * 这个时候,我们不希望数据在内存中呆太久,最好能够做到同步,这是我们的需求。<br>
  14. * 第一种方案:<br>
  15. * 1. RandomAccessFile<br>
  16. * 2. public RandomAccessFile(File file, String mode) throws FileNotFoundException<br>
  17. * Constructs a new RandomAccessFile based on file and opens it according to the access string in mode. <br>
  18. * 3. mode may have one of following values: <br>
  19. * 1. "r" The file is opened in read-only mode. An IOException is thrown if any of the write methods is called. <br>
  20. * 2. "rw" The file is opened for reading and writing. If the file does not exist, it will be created. <br>
  21. * 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>
  22. * 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>
  23. * 4. 由于我们需要其中的数据同步功能,所以我们选择使用包装RandomAccessFile类,实现要求。<br>
  24. * 第二种方案:<br>
  25. * 1. FileDescriptor中有sync()方法<br>
  26. Ensures that data which is buffered within the underlying implementation is written out to the appropriate device before returning.<br>
  27. * 2. FileOutputStream中的 getFD()方法<br>
  28. Returns a FileDescriptor which represents the lowest level representation of an operating system stream resource. <br>
  29. * 3. 使用起来感觉没有RandomAccessFile方便,放弃时使用<br>
  30. */
  31.  
  32. public class ZengjfRandomAccessFile {
  33. /**
  34. * 将整形数组写入文件
  35. *
  36. * @param filePath 文件路径
  37. * @param data 整形数组
  38. * @throws IOException
  39. */
  40. static public void writeIntArray(String filePath, int[] data) throws IOException {
  41. if (null == filePath || null == data)
  42. return ;
  43.  
  44. if (filePath.trim().equals(""))
  45. return ;
  46.  
  47. File file = new File(filePath);
  48. if (!file.exists())
  49. file.createNewFile();
  50.  
  51. if (!file.canWrite())
  52. throw new RuntimeException("Zengjf Utils writeIntArray(): no permission for file -- " + filePath + ".");
  53.  
  54. // write data
  55. RandomAccessFile raf = new RandomAccessFile(file, "rws");
  56. for (int i = 0; i < data.length; i++)
  57. raf.writeInt(data[i]);
  58.  
  59. raf.close();
  60. }
  61.  
  62. /**
  63. * 将整形数组写入文件,文件目录被指定,作为使用者可以不用关心
  64. *
  65. * @param activity 调用这个函数的Activity
  66. * @param data 要保存的的整形数组
  67. * @throws IOException
  68. */
  69. static public void writeIntArray(Activity activity, int[] data) throws IOException {
  70. if (null == activity || null == data)
  71. return ;
  72.  
  73. String filePath = activity.getApplicationContext().getFilesDir().getAbsoluteFile() + "/zengjfData.txt";
  74. writeIntArray(filePath, data);
  75. }
  76.  
  77. /**
  78. * 从文件中读出长度为length的整形数组
  79. *
  80. * @param filePath 文件路径
  81. * @param length 数组长度
  82. * @return 返回数组,如果出错,返回null
  83. * @throws IOException
  84. */
  85. static public int[] readIntArray(String filePath, int length) throws IOException {
  86.  
  87. if (null == filePath || length <= 0)
  88. return null;
  89.  
  90. if (filePath.trim().equals(""))
  91. return null;
  92.  
  93. File file = new File(filePath);
  94. if (!file.canRead())
  95. throw new RuntimeException("Zengjf Utils writeIntArray(): no permission for file -- " + filePath + ".");
  96.  
  97. int[] data = new int[length]; // for return data
  98.  
  99. // if file not exist in first time and file length less than data size,
  100. // just create file and make data for it
  101. if (!file.exists() || (file.length() < (4 * length))) {
  102. for (int i = 0; i < data.length; i++)
  103. data[i] = 0;
  104.  
  105. writeIntArray(filePath, data);
  106. return data;
  107. }
  108.  
  109. //get data
  110. RandomAccessFile raf = new RandomAccessFile(file, "r");
  111. for (int i = 0; i < length; i++)
  112. data[i] = raf.readInt();
  113.  
  114. raf.close();
  115.  
  116. return data;
  117. }
  118.  
  119. /**
  120. * 从文件中读取整形数组,文件位置、名已经被指定,作为使用者可以不关心
  121. *
  122. * @param activity 调用这个函数的Activity
  123. * @param length 数组的长度
  124. * @return 返回数组,如果出错,返回null
  125. * @throws IOException
  126. */
  127. static public int[] readIntArray(Activity activity, int length) throws IOException {
  128. if (null == activity || 0 == length)
  129. return null;
  130.  
  131. String filePath = activity.getApplicationContext().getFilesDir().getAbsoluteFile() + "/zengjfData.txt";
  132. return readIntArray(filePath, length);
  133. }
  134.  
  135. /**
  136. * 往文件中写入原始整形数组,其实就是填充整形0
  137. *
  138. * @param filePath 文件路径
  139. * @param length 数组大小
  140. * @throws IOException
  141. */
  142. static public void writeRawIntArray(String filePath, int length) throws IOException {
  143.  
  144. if (null == filePath || length <= 0)
  145. return ;
  146.  
  147. if (filePath.trim().equals(""))
  148. return ;
  149.  
  150. File file = new File(filePath);
  151. int[] data = new int[length]; // for return data
  152.  
  153. // if file not exist in first time, just create file and make data for it
  154. if (file.exists()) {
  155. for (int i = 0; i < data.length; i++)
  156. data[i] = 0;
  157.  
  158. writeIntArray(filePath, data);
  159. }
  160. }
  161.  
  162. /**
  163. *
  164. * 往文件中写入值为0的整形数组,文件位置、名已经被指定,作为使用者可以不关心
  165. *
  166. * @param activity 调用这个函数的Activity
  167. * @param length 写入数组的长度
  168. * @throws IOException
  169. */
  170. static public void writeRawIntArray(Activity activity, int length) throws IOException{
  171. if (null == activity || 0 == length)
  172. return ;
  173.  
  174. String filePath = activity.getApplicationContext().getFilesDir().getAbsoluteFile() + "/zengjfData.txt";
  175. writeRawIntArray(filePath, length);
  176. }
  177.  
  178. /**
  179. * 测试用的的Demo
  180. * @param activity 调用这个函数的Activity
  181. */
  182. static public void testDemo(Activity activity) {
  183. int[] data = {1, 2, 3, 4, 5, 6};
  184. try {
  185. writeIntArray(activity, data);
  186. int[] redata = readIntArray(activity, 6);
  187. Log.e("zengjf utils", Arrays.toString(redata));
  188. } catch (IOException e) {
  189. // TODO Auto-generated catch block
  190. e.printStackTrace();
  191. }
  192. }
  193. }

Android App data write as file data with synchronous Demo的更多相关文章

  1. 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 ...

  2. 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””] ...

  3. [转]在eclipse打开的android虚拟手机,打开File Explorer,下面是空的没有data、mnt、system三个文件

    在eclipse打开的android虚拟手机,打开File Explorer,下面是空的没有data.mnt.system三个文件 这是因为模拟器没有选择打开的缘故,必须首先打开一个模拟器(AVD), ...

  4. 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 ...

  5. Android 程序drawable资源保存到data目录

    今天做了个小功能,就是把我们程序Drawable里面的图片保存到data目录下面,然后另外一个程序需要读取data目录里面保存的图片.涉及了data目录读写.这功能看上去挺简单,不过实际做的时候还是遇 ...

  6. android:Intent匹配action,category和data原则

    1.当你在androidmanifest里面定义了一个或多个action时 你使用隐式意图其他activity或者service时,规定你隐式里面的action必须匹配XML中定义的action,可以 ...

  7. 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 ...

  8. 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 ...

  9. couldn't open file: data/coco.names

    在ubuntu下配置yolo(v2)的时候,编译了源码后,尝试运行demo: ./darknet detect cfg/yolo.cfg yolo.weights data/dog.jpg 结果报错提 ...

随机推荐

  1. 《剑指offer》第二十四题(反转链表)

    // 面试题24:反转链表 // 题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的 // 头结点. #include <iostream> #include &quo ...

  2. Spring AMQP 源码分析 05 - 异常处理

    ### 准备 ## 目标 了解 Spring AMQP Message Listener 如何处理异常 ## 前置知识 <Spring AMQP 源码分析 04 - MessageListene ...

  3. git/ssh备查文档

    配置多个ssh key: 待更新 git速查表: git remote set-url origin(远程仓库名称) https://xxxxx/ProjectName.git  从ssh切换至htt ...

  4. mate桌面xrdp无法登陆问题

    vi /usr/libexec/xrdp/startwm.sh 或者/etc/xrdp/startwm.sh: 找到相应的发行版本,增加mate-session如下所示: # el  if [ -r ...

  5. Mashmokh and ACM CodeForces - 414D (贪心)

    大意: 给定n结点树, 有k桶水, p块钱, 初始可以任选不超过k个点(不能选根结点), 在每个点放一桶水, 然后开始游戏. 游戏每一轮开始时, 可以任选若干个节点关闭, 花费为关闭结点储存水的数量和 ...

  6. php实现频率限制

    一.前言 公司要做呼叫中心,呼叫中心为了防止骚扰,需要限制用户拨打电话的频率,比如30s只能点击一次.这样的需求是通过redis来实现的. 二.具体实现 <?php class Resource ...

  7. dp练习(3)——棋盘问题

    设有一个n*m的棋盘(2≤n≤50,2≤m≤50),如下图,在棋盘上有一个中国象棋马. 规定: 1)马只能走日字 2)马只能向右跳 问给定起点x1,y1和终点x2,y2,求出马从x1,y1出发到x2, ...

  8. 学习总结(ASP.NET MVC 5)

    1. 无论什么时候,如果要写一个新的 MVC 的程序(网站),打开VS之后第一步永远都是“创建新的 ASP.NET MVC 项目” (“新建项目”—→“Web(Visual C#)”—→“ASP.NE ...

  9. form数据请求参数格式

    请求后台参数格式问题 当请求后台传递参数时,有多中类型,而每一种都需要前后台进行配合,而这有时候会很简单,有时候却十分困难,记录一下,以备后期深究 数据 后台需要的数据 form表单 嵌套数据,第二层 ...

  10. hadoop mysql install (5)

    reference : http://dblab.xmu.edu.cn/blog/install-mysql/ http://wiki.ubuntu.org.cn/MySQL #install mys ...