Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Read Primitive File

Problem - How you can read primitive data types from a file?

Solution :
java.io.RandomAccessFile behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer.

Prerequisite:-
You must create Write Primitive File first to run this program.

Program :

Step 1 - Coding

Create a text file c:/sunilos/ReadPrimitiveFile.java and copy below contents.

import java.io.RandomAccessFile;

/**
 * A program to read primitive data types in a file.
 */ 

public class ReadPrimitiveFile {

    public static void main(String[] args) throws Exception {
        long dataPosition=0;
        long data = 0;
        RandomAccessFile raf = new RandomAccessFile("c:/sunilos/sunilosfile.dat","r");
       
        dataPosition = raf.readLong();
       
        System.out.println("dataPosition : " +dataPosition);
       
        raf.seek(dataPosition);
        data = raf.readInt();
        raf.close();
        System.out.println("The dat is : " +data);
       
    }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy ReadPrimitiveFile.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile ReadPrimitiveFile.java with help of 
    • javac ReadPrimitiveFile.java command. Command will create ReadPrimitiveFile.class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java ReadPrimitiveFile command.

Output


dataPosition : 32
The dat is : 1114399080

<<Previous | Next>>
ċ
ReadPrimitiveFile.java
(1k)
Mahima Hardia,
Aug 19, 2011, 3:31 AM
Comments