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

Write Primitive Data

Problem - How you can write primitive data types into a file?

Solution :
java.io.FileOutputStream is an output stream for writing data to a file. java.io.DataOutputStream converts primitive data into byte stream.

Program :

Step 1 - Coding

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

import java.io.DataOutputStream;
import java.io.FileOutputStream;

/**
 * A program to write primitive data types.
 */ 

public class WritePrimitiveData {

    public static void main(String[] args) throws Exception{

        FileOutputStream file = new FileOutputStream("c:/sunilos/sunilos.dat");
       
        DataOutputStream out = new DataOutputStream(file);
       
        out.writeInt(1);
        out.writeBoolean(true);
        out.writeChar('A');
        out.writeDouble(1.2);
       
        out.close();
        System.out.println("Primitive Data successfully written");
       
    }

}

Step 2 - Deployment

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

Output

Primitive Data successfully written

<<Previous | Next>>

ċ
WritePrimitiveData.java
(1k)
Mahima Hardia,
Aug 19, 2011, 3:25 AM
Comments