Java DataOutputStream Class

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.

Java DataOutputStream class declaration

Let’s see the declaration for java.io.DataOutputStream class:

  1. public class DataOutputStream extends FilterOutputStream implements DataOutput

Java DataOutputStream class methods

Method Description
int size() It is used to return the number of bytes written to the data output stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
void writeBytes(String s) It is used to write string to the output stream as a sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.

 

Example of DataOutputStream class

In this example, we are writing the data to a text file testout.txt using DataOutputStream class.

  1. package com.javatpoint;
  2. import java.io.*;
  3. public class OutputExample {
  4.     public static void main(String[] args) throws IOException {
  5.         FileOutputStream file = new FileOutputStream(D:\\testout.txt);
  6.         DataOutputStream data = new DataOutputStream(file);
  7.         data.writeInt(65);
  8.         data.flush();
  9.         data.close();
  10.         System.out.println(“Succcess…”);
  11.     }
  12. }

Output:

Succcess...

testout.txt:

A
java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

Java DataOutputStream Class Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way. Java application generally uses the data output stream to write data that can later be read by a data input stream. Java DataOutputStream class declaration Let’s see the declaration for java.io.DataOutputStream class: […]

Tags:

....
...