Random File : Files « File Input Output « Java






Random File

Random File
  

import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomFileTest {
  public static void main(String[] args) {
    Employee[] staff = new Employee[3];

    staff[0] = new Employee("Harry Hacker", 35000);
    staff[1] = new Employee("Carl Cracker", 75000);
    staff[2] = new Employee("Tony Tester", 38000);
    try {
      DataOutputStream out = new DataOutputStream(new FileOutputStream(
          "employee.dat"));
      for (int i = 0; i < staff.length; i++)
        staff[i].writeData(out);
      out.close();
    } catch (IOException e) {
      System.out.print("Error: " + e);
      System.exit(1);
    }

    try {
      RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
      int count = (int) (in.length() / Employee.RECORD_SIZE);
      Employee[] newStaff = new Employee[count];

      for (int i = count - 1; i >= 0; i--) {
        newStaff[i] = new Employee();
        in.seek(i * Employee.RECORD_SIZE);
        newStaff[i].readData(in);
      }
      for (int i = 0; i < newStaff.length; i++)
        newStaff[i].print();
    } catch (IOException e) {
      System.out.print("Error: " + e);
      System.exit(1);
    }
  }
}

class Employee {
  public static final int NAME_SIZE = 40;

  public static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4;

  private String name;

  private double salary;

  public Employee(String n, double s) {
    name = n;
    salary = s;
  }

  public Employee() {
  }

  public void print() {
    System.out.println(name + " " + salary);
  }
  public void writeData(DataOutput out) throws IOException {
    DataIO.writeFixedString(name, NAME_SIZE, out);
    out.writeDouble(salary);
  }

  public void readData(DataInput in) throws IOException {
    name = DataIO.readFixedString(NAME_SIZE, in);
    salary = in.readDouble();
  }
}

class DataIO {
  public static String readFixedString(int size, DataInput dataInput)
      throws IOException {
    StringBuffer strBuffer = new StringBuffer(size);
    int count = 0;
    boolean more = true;
    while (more && count < size) {
      char aChar = dataInput.readChar();
      count++;
      if (aChar == 0)
        more = false;
      else
        strBuffer.append(aChar);
    }
    dataInput.skipBytes(2 * (size - count));
    return strBuffer.toString();
  }

  public static void writeFixedString(String str, int size, DataOutput dataOutput)
      throws IOException {

    for (int i = 0; i < size; i++) {
      char aChar = 0;
      if (i < str.length())
        aChar = str.charAt(i);
      dataOutput.writeChar(aChar);
    }
  }
}
           
         
    
  








Related examples in the same category

1.Create file
2.Create a temporary file
3.Creating a Temporary File and delete it on exit
4.Create a directory (or several directories)
5.Get file size
6.Change last modified time of a file or directory
7.Construct file path
8.Create temporary file with specified extension suffix
9.Create temporary file in specified directory
10.Create new empty file
11.Compare two file paths
12.Delete a file
13.Delete file or directory
14.Deleting a Directory (an empty directory)
15.Delete file or directory when virtual machine terminates
16.Determine File or Directory
17.Determine if a file can be read
18.Determine if a file can be written
19.Determine if file or directory exists
20.Determine if File or Directory is hidden
21.Demonstrate File.
22.Moving a File or Directory to Another Directory
23.Find out the directoryFind out the directory
24.Get all path information from java.io.File
25.Getting an Absolute Filename Path from a Relative Filename Path
26.Getting an Absolute Filename Path from a Relative Filename with Path
27.Getting an Absolute Filename Path from a Relative Filename parent Path
28.Get Absolute path of the file
29.Get File size in bytes
30.Get parent directory as a File object
31.Get a file last modification date
32.File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.
33.Getting the Parents of a Filename Path
34.Get the parents of an absolute filename path
35.Getting and Setting the Modification Time of a File or Directory
36.Mark file or directory Read Only
37.List Filesystem roots
38.List drives
39.Listing the Directory ContentsListing the Directory Contents
40.Rename file or directory
41.Forcing Updates to a File to the Disk
42.Create a directory; all ancestor directories must exist
43.Create a directory; all non-existent ancestor directories are automatically created
44.Getting the Current Working Directory
45.Change a file attribute to writable
46.Data fileData file
47.Output to a text File
48.Choose a FileChoose a File
49.Read data from text file
50.Copy File
51.Querying a File for Information
52.Working with RandomAccessFileWorking with RandomAccessFile
53.Get a list of files, and check if any files are missing
54.Delete a file from within Java
55.Work with temporary files in Java
56.Compare File Dates
57.Sort files base on their last modified date
58.Strings -- extract printable strings from binary file
59.Get extension, path and file nameGet extension, path and file name
60.Read file contents to string using commons-io?
61.Get all xml files by file extension
62.Get icon for file type
63.Change a file attribute to read only
64.Get file extension name
65.Search for files recursively
66.Create a human-readable file size
67.Set file attributes.
68.Format file length in string
69.Return a file with the given filename creating the necessary directories if not present.