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

Write Primitive File

Problem : How you can read/write to primitive 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.

Program :

Step 1 - Coding

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

import java.io.RandomAccessFile;

 * A program to write primitive data types in a file.

public class WritePrimitiveFile {

    public static void main(String[] args) throws Exception{
        long dataPosition = 0;
        RandomAccessFile in = new RandomAccessFile("c:/sunilos/sunilosfile.dat","rw");
        dataPosition = in.getFilePointer();


Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy WritePrimitiveFile.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile WritePrimitiveFile.java with help of 
    • javac WritePrimitiveFile.java command.Command will create WritePrimitiveFile.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 WritePrimitiveFile command.

<<Previous | Next>>
Namrata Sisodiya,
Aug 19, 2011, 3:29 AM