Using RandomAccessFile to read file saved DataOutputStream : RandomAccessFile « File Input Output « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » File Input Output » RandomAccessFileScreenshots 
Using RandomAccessFile to read file saved DataOutputStream
Using RandomAccessFile to read file saved DataOutputStream
 

/*
   This program is a part of the companion code for Core Java 8th ed.
   (http://horstmann.com/corejava)

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 @version 1.11 2004-05-11
 @author Cay Horstmann
 */
public class RandomFileTest
{  
   public static void main(String[] args)
   {
      Employee[] staff = new Employee[3];

      staff[0new Employee("Carl Cracker"7500019871215);
      staff[1new Employee("Harry Hacker"500001989101);
      staff[2new Employee("Tony Tester"400001990315);

      try
      {  
         // save all employee records to the file employee.dat
         DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));
         for (Employee e : staff)
            e.writeData(out);
         out.close();
      
         // retrieve all records into a new array
         RandomAccessFile in = new RandomAccessFile("employee.dat""r");   
         // compute the array size
         int n = (int)(in.length() / Employee.RECORD_SIZE);
         Employee[] newStaff = new Employee[n];

         // read employees in reverse order
         for (int i = n - 1; i >= 0; i--)
         {  
            newStaff[inew Employee();
            in.seek(i * Employee.RECORD_SIZE);
            newStaff[i].readData(in);
         }
         in.close();
         
         // print the newly read employee records
         for (Employee e : newStaff
            System.out.println(e);
      }
      catch (IOException e)
      {  
         e.printStackTrace()
      }
   }
}

class Employee
{
   public Employee() {}

   public Employee(String n, double s, int year, int month, int day)
   {  
      name = n;
      salary = s;
      GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
      hireDay = calendar.getTime();
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public Date getHireDay()
   {  
      return hireDay;
   }

   /**
      Raises the salary of this employee.
      @byPercent the percentage of the raise
   */
   public void raiseSalary(double byPercent)
   {  
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   public String toString()
   {  
      return getClass().getName()
         "[name=" + name
         ",salary=" + salary
         ",hireDay=" + hireDay
         "]";
   }

   /**
      Writes employee data to a data output
      @param out the data output
   */
   public void writeData(DataOutput outthrows IOException
   {
      DataIO.writeFixedString(name, NAME_SIZE, out);
      out.writeDouble(salary);

      GregorianCalendar calendar = new GregorianCalendar();
      calendar.setTime(hireDay);
      out.writeInt(calendar.get(Calendar.YEAR));
      out.writeInt(calendar.get(Calendar.MONTH1);
      out.writeInt(calendar.get(Calendar.DAY_OF_MONTH));
   }

   /**
      Reads employee data from a data input
      @param in the data input
   */
   public void readData(DataInput inthrows IOException
   {
      name = DataIO.readFixedString(NAME_SIZE, in);
      salary = in.readDouble();
      int y = in.readInt();
      int m = in.readInt();
      int d = in.readInt();
      GregorianCalendar calendar = new GregorianCalendar(y, m - 1, d);
      hireDay = calendar.getTime();
   }

   public static final int NAME_SIZE = 40;
   public static final int RECORD_SIZE = * NAME_SIZE + 4;

   private String name;
   private double salary;
   private Date hireDay;
}

class DataIO
{
   public static String readFixedString(int size, DataInput in
      throws IOException
   {  
      StringBuilder b = new StringBuilder(size);
      int i = 0;
      boolean more = true;
      while (more && i < size)
      {  
         char ch = in.readChar();
         i++;
         if (ch == 0more = false;
         else b.append(ch);
      }
      in.skipBytes((size - i));
      return b.toString();
   }

   public static void writeFixedString(String s, int size, DataOutput out
      throws IOException
   {
      for (int i = 0; i < size; i++)
      {  
         char ch = 0;
         if (i < s.length()) ch = s.charAt(i);
         out.writeChar(ch);
      }
   }
}

   
  
Related examples in the same category
1.Random IO
2.Using the RandomAccessFile class
3.The RandomAccessFile Class
4.Use RandomAccessFile to reverse a file
5.Using a Random Access File
6.A RandomAccessFile object that is tied to a file called employee.dat.
7.Reading UTF-8 Encoded Data
8.Use RandomAccessFile class
9.Appending data to existing file
10.The class demonstrates the use of java.io.RandomAccessFile
11.Readonly RandomAccessFile
12.Translate Charset
13.Use RandomAccessFile to save an object
14.Reverse a file with RandomAccessFile
15.Read from back
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.