1. // DataInputStream类实现了DataInput接口,要想从文件中读入二进制数据,
  2. // 你需要将DataInputStream与某个字节源相结合,例如FileInputStream
  3. // 与此同时,要想写出二进制数据,可以使用实现了DataOutput接口的DataOutputStream类
  4. // RandomAccessFile类同时实现了DataInput和DataOutput接口。
  5. // 以下程序将三条记录写到一个数据文件中,然后以逆序将它们从文件中读回。
  6. // 为了高效地执行,这里需要使用随机访问,因为我们需要首先读入第三条记录
  7. // 让我们来计算每条记录的大小:我们将使用40个字符来 表示姓名字符串,因此每条记录包含100个字节:
  8. // 40字符 = 80字节,用于姓名
  9. // 1 double = 8字节,用于薪水
  10. // 3 int = 12字节,用于日期
  11. package com.example.io;
  12.  
  13. import java.io.DataInput;
  14. import java.io.DataOutput;
  15. import java.io.DataOutputStream;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import java.io.RandomAccessFile;
  19. import java.util.Calendar;
  20. import java.util.Date;
  21. import java.util.GregorianCalendar;
  22.  
  23. public class RandomFileTest {
  24.  
  25. public static void main(String[] args) {
  26. Employee[] staff = new Employee[3];
  27.  
  28. staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
  29. staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
  30. staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
  31.  
  32. try {
  33. // 保存所有雇员记录到文件当中
  34. DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));
  35. for (Employee e : staff) {
  36. e.writeData(out);
  37. }
  38. out.close();
  39.  
  40. // 读取所有记录到新数组中
  41. RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
  42. // 计算数组的尺寸
  43. int n = (int) (in.length() / Employee.RECORD_SIZE);
  44. Employee[] newStaff = new Employee[n];
  45.  
  46. //反序读入雇员记录
  47. for (int i = n - 1, j = 0; i >= 0; i--) {
  48. newStaff[j] = new Employee();
  49. in.seek(i * Employee.RECORD_SIZE);
  50. newStaff[j].readData(in);
  51. j++;
  52. }
  53. in.close();
  54.  
  55. // 打印新读入数组记录内容
  56. for (Employee e : newStaff) {
  57. System.out.println(e);
  58. }
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. }
  62.  
  63. }
  64.  
  65. }
  66.  
  67. class Employee {
  68.  
  69. public Employee() {
  70. }
  71.  
  72. public Employee(String n, double s, int year, int month, int day) {
  73. name = n;
  74. salary = s;
  75. GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
  76. hireDay = calendar.getTime();
  77. }
  78.  
  79. public String getName() {
  80. return name;
  81. }
  82.  
  83. public double getSalary() {
  84. return salary;
  85. }
  86.  
  87. public Date getHireDay() {
  88. return hireDay;
  89. }
  90.  
  91. public void raiseSalary(double byPercent) {
  92. double raise = salary * byPercent / 100;
  93. salary += raise;
  94. }
  95.  
  96. @Override
  97. public String toString() {
  98. return "Employee{" + "name=" + name + ", salary=" + salary + ", hireDay=" + hireDay + '}';
  99. }
  100.  
  101. public void writeData(DataOutput out) throws IOException {
  102. DataIO.writeFixedString(name, NAME_SIZE, out);
  103. out.writeDouble(salary);
  104.  
  105. GregorianCalendar calendar = new GregorianCalendar();
  106. calendar.setTime(hireDay);
  107. out.writeInt(calendar.get(Calendar.YEAR));
  108. out.writeInt(calendar.get(Calendar.MONTH) + 1);
  109. out.writeInt(calendar.get(Calendar.DAY_OF_MONTH));
  110. }
  111.  
  112. public void readData(DataInput in) throws IOException {
  113. name = DataIO.readFixedString(NAME_SIZE, in);
  114. salary = in.readDouble();
  115. int y = in.readInt();
  116. int m = in.readInt();
  117. int d = in.readInt();
  118. GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d);
  119. hireDay = calendar.getTime();
  120. }
  121.  
  122. public static final int NAME_SIZE = 40;
  123. public static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4;
  124. private String name;
  125. private double salary;
  126. private Date hireDay;
  127. }
  128.  
  129. class DataIO {
  130.  
  131. public static String readFixedString(int size, DataInput in) throws IOException {
  132. StringBuilder b = new StringBuilder(size);
  133. int i = 0;
  134. boolean more = true;
  135. while (more && i < size) {
  136. char ch = in.readChar();
  137. i++;
  138. if (ch == 0) {
  139. more = false;
  140. } else {
  141. b.append(ch);
  142. }
  143. }
  144. in.skipBytes(2 * (size - i));
  145. return b.toString();
  146. }
  147.  
  148. public static void writeFixedString(String s, int size, DataOutput out) throws IOException {
  149. for (int i = 0; i < size; i++) {
  150. char ch = 0;
  151. if (i < s.length()) {
  152. ch = s.charAt(i);
  153. }
  154. out.writeChar(ch);
  155. }
  156. }
  157. }

DataInputStream类和RandomAccessFile类的使用方法的更多相关文章

  1. [Java IO]01_File类和RandomAccessFile类

    File类 File类是java.io包中唯一对文件本身进行操作的类.它可以进行创建.删除文件等操作.   File类常用操作 (1)创建文件 可以使用 createNewFille() 创建一个新文 ...

  2. File类和RandomAccessFile类

    目录 File类     File类常用操作     (1)创建文件     (2)删除文件     (3)创建文件夹     (4)列出指定目录全部文件     (5)删除目录 RandomAcce ...

  3. 通过扩展RandomAccessFile类使之具备Buffer改善I/O性能--转载

    主体: 目前最流行的J2SDK版本是1.3系列.使用该版本的开发人员需文件随机存取,就得使用RandomAccessFile类.其I/O性能较之其它常用开发语言的同类性能差距甚远,严重影响程序的运行效 ...

  4. Java基础(二十八)Java IO(5)RandomAccessFile类与过滤器流(Filter Stream)

    一.RandomAccessFile类 使用RandomAccessFile类可以读取任意位置数据的文件. 1.构造方法 RandomAccessFile(String name, String mo ...

  5. 在对文件进行随机读写,RandomAccessFile类,如何提高其效率

    花1K内存实现高效I/O的RandomAccessFile类 JAVA的文件随机存取类(RandomAccessFile)的I/O效率较低.通过分析其中原因,提出解决方案.逐步展示如何创建具备缓存读写 ...

  6. RandomAccessFile类

    File类只是针对文件本身进行操作,而如果要对文件内容进行操作,则可以使用RandomAccessFile类,此类属于随机读取类,可以随机地读取一个文件中指定位置的数据. //============ ...

  7. 使用RandomAccessFile类对文件进行读写

    1. RandomAccessFile类简介   前面一篇随笔<File类遍历目录及文件>中有说到,File类只能用于表示文件或目录的名称.大小等信息,而不能用于文件内容的访问.而当需要访 ...

  8. 【Java IO流】RandomAccessFile类的使用

    RandomAccessFile类的使用 RandomAccessFile类是java提供的对文件内容的访问,既可以读文件,也可以写文件. 支持随机访问文件,可以访问文件的任意位置. RandomAc ...

  9. 输入和输出--RandomAccessFile类

    RandomAccessFile 类 RandomAccessFile 类既可以读取文件内容,也可以向文件输出数据. RandomAccessFile 类支持 "随机访问" 的方式 ...

随机推荐

  1. How to configure windows machine to allow file sharing with dns alias (CNAME)

    Source: http://serverfault.com/questions/23823/how-to-configure-windows-machine-to-allow-file-sharin ...

  2. Asp.Net Web API 2第十四课——Content Negotiation(内容协商)

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文描述ASP.NET W ...

  3. 【点滴javascript】变量与作用域

    基本类型与引用类型 ECMAScript的的变量有两种类型: 基本类型(值类型):简单数据段 引用类型:多个值构成的对象 在变量赋值结束后,解析器必须知道这个变量时基本数据类型还是引用类型,需要注意的 ...

  4. jQuery的XX如何实现?——4.类型检查

    往期回顾: jQuery的XX如何实现?——1.框架 jQuery的XX如何实现?——2.show与链式调用 jQuery的XX如何实现?——3.data与cache机制 -------------- ...

  5. django with mysql (part-3)

    step01: write second view-function vim views.py step02: configure your ( urls.py ) vim urls.py step0 ...

  6. 02_Hello World!

    hello word ? 学习任何语言,我们都喜欢在屏幕上直接输出一点什么,作为最简单基本的案例.很多人习惯输出 hello world ,世界你好.感觉很有情况的样子——然而很多人都只停留在这个阶段 ...

  7. paip.性能跟踪profile原理与架构与本质-- python扫带java php

    paip.性能跟踪profile原理与架构与本质-- python扫带java php ##背景 弄个个输入法音标转换atiEnPH工具,老是python性能不的上K,7k记录浏览过k要30分钟了. ...

  8. APP顶号逻辑

    登录的接口login.do接口上需要记录关键的信息:userId.设备型号(Android|iPhone).登录时间.登录IP.设备唯一标识(UUID) 当在另外一台新设备上登录同一帐号时,将user ...

  9. iOS 9 failed for URL: "XXX://@" - error: "This app is not allowed to query for scheme XXX" iOS 从APP里启动另一APP

    iOS 从C APP里启动 D APP 首先在D APP里设置 URL Schemes 在info.plist 文件里添加URL Schemes URL Types -->item0 --> ...

  10. 2016年 最火的 15 款 HTML5 游戏引擎

    HTML5游戏从2014年Egret引擎开发的神经猫引爆朋友圈之后,就开始一发不可收拾,今年<传奇世界>更是突破流水2000万!从两年多的发展来看,游戏开发变得越来越复杂,需要制作各种炫丽 ...