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");
       
        in.writeLong(0);
        in.writeChars("blahblahblah");
        dataPosition = in.getFilePointer();
        in.writeBytes("Blahblahblah");
       
        in.seek(0);
        in.writeLong(dataPosition);
        in.close();
       
   
    }

}

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>>
ċ
WritePrimitiveFile.java
(1k)
Mahima Hardia,
Aug 19, 2011, 3:29 AM
Comments