Sunday, 11 June 2017

Java Tutorial : Java IO (DataOutputStream DataInputStream Example) ~ foundjava


Click here to watch in Youtube : 

DataOutputStreamDemo.java
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo
{

    public static void main(String[] args) throws Exception
    {
        DataOutputStreamDemo dataOutputStreamDemo = new DataOutputStreamDemo();
        dataOutputStreamDemo.writePrimitiveData();
    }

    public void writePrimitiveData() throws IOException
    {
        DataOutputStream dataOutputStream = null;
        FileOutputStream fileOutputStream = null;
        try
        {
            fileOutputStream = new FileOutputStream("data.txt");
            dataOutputStream = new DataOutputStream(fileOutputStream);
            int[] intArray = { 100, 250, 440, 550, 900 };

            for (int j : intArray)
            {
                dataOutputStream.writeInt(j);
            }

            System.out.println("Successfully written to \'data.txt\' file\n");
        }
        finally
        {
            if (dataOutputStream != null)
            {
                /*
                 * Closing a DataOutputStream will also
                 * close the OutputStream instance to which
                 * the DataOutputStream is writing.
                 */
                dataOutputStream.close();
            }
        }

    }
}
Output
Successfully written to 'data.txt' file
data.txt
DataInputStreamDemo.java
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class DataInputStreamDemo
{

    public static void main(String[] args) throws Exception
    {
        DataInputStreamDemo dataInputStreamDemo = new DataInputStreamDemo();
        dataInputStreamDemo.readPrimitiveData();
    }

    public void readPrimitiveData() throws IOException
    {
        FileInputStream fileInputStream = null;
        DataInputStream dataInputStream = null;

        try
        {
            fileInputStream = new FileInputStream("data.txt");
            dataInputStream = new DataInputStream(fileInputStream);

            while (dataInputStream.available() > 0)
            {
                int intValue = dataInputStream.readInt();
                System.out.println(intValue);
            }

        }
        finally
        {
            if (dataInputStream != null)
            {
                /*
                 * Closing a DataInputStream will also close
                 * the InputStream instance from which the
                 * DataInputStream is reading.
                 */
                dataInputStream.close();
            }
        }

    }

}
Output
100
250
440
550
900

Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment