Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Useful Resources

Java - DataOutputStream



The DataOutputStream stream lets you write the primitives to an output source.

Following is the constructor to create a DataOutputStream.

DataOutputStream out = DataOutputStream(OutputStream out);

Once you have DataOutputStream object in hand, then there is a list of helper methods, which can be used to write the stream or to do other operations on the stream.

Sr.No. Method & Description
1

public final void write(byte[] w, int off, int len)throws IOException

Writes len bytes from the specified byte array starting at point off, to the underlying stream.

2

Public final int write(byte [] b)throws IOException

Writes the current number of bytes written to this data output stream. Returns the total number of bytes written into the buffer.

3

(a) public final void writeBooolean()throws IOException,

(b) public final void writeByte()throws IOException,

(c) public final void writeShort()throws IOException

(d) public final void writeInt()throws IOException

These methods will write the specific primitive type data into the output stream as bytes.

4

Public void flush()throws IOException

Flushes the data output stream.

5

public final void writeBytes(String s) throws IOException

Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.

Example

Following is an example to demonstrate DataInputStream and DataOutputStream. This example reads 5 lines given in a file test.txt and converts those lines into capital letters and finally copies them into another file test1.txt.

import java.io.*;
public class DataInput_Stream {

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

      // writing string to a file encoded as modified UTF-8
      DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
      dataOut.writeUTF("hello");

      // Reading data from the same file
      DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));

      while(dataIn.available()>0) {
         String k = dataIn.readUTF();
         System.out.print(k+" ");
      }
   }
}

Here is the sample run of the above program −

Output

THIS IS TEST 1  ,
THIS IS TEST 2  ,
THIS IS TEST 3  ,
THIS IS TEST 4  ,
THIS IS TEST 5  ,
java_files_io.htm
Advertisements