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

Read Primitive Data

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

Solution :
java.io.DataInputStream  is use to converts  bytes into primitive data types. java.io.DataInputStream is connect with java.io.FileInputStream to get bytes from a file.

Prerequisite:-  Primitive data has been written to a file with help of previous program.

Program :

Step 1 - Coding


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

import java.io.DataInputStream;
import java.io.FileInputStream;

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

public class ReadPrimitiveData {

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

        FileInputStream file = new FileInputStream("c:/sunilos/sunilos.dat");
       
        DataInputStream in = new DataInputStream(file);
       
        System.out.println(in.readInt());
        System.out.println(in.readBoolean());
        System.out.println(in.readChar());
        System.out.println(in.readDouble());
        in.close();
       
    }

}

Step 2 - Deployment

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

Output


1
true
A
1.2

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