java tutorial - Java - DataOutputStream class and its methods - java programming - learn java - java basics - java for beginners



The DataOutputStream stream allows you to write primitive data into the source code.

  • The following is a constructor for creating a DataOutputStream:
DataOutputStream out = DataOutputStream(OutputStream out);
click below button to copy the code. By - java tutorial - team

Methods

If you use the DataOutputStream object, then you have on hand ancillary methods that you can use to write the stream or perform other operations on the stream.

No. Method and Description
1 public final void write (byte [] w, int off, int len) throws IOException
Write len bytes from the specified byte array, starting from off, to the main stream.
2 public final int write (byte [] b) throws IOException
Record the current number of bytes written to this output data stream (DataOutputStream).
3 (1) public final void writeBooolean () throws IOException
(2) public final void writeByte () throws IOException
(3) public final void writeShort () throws IOException
(4) public final void writeInt () throws IOException
These methods will write data of a certain primitive type to the output stream as bytes.
4 Public void flush () throws IOException
Resets the output stream.
5 public final void writeBytes (String s) throws IOException
Writes a string to the main output stream as a sequence of bytes. Each character in the line is written eight bits.

Sample Code

Below is an example of demonstrating DataInputStream and DataOutputStream. This example writes and reads from the specified file test.txt.

import java.io.*;
public class TestByteStream {

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

      // Writing a string to a file encoded in UTF-8
      DataOutputStream dataOutput = new DataOutputStream(new FileOutputStream("E:\\test.txt"));
      dataOutput.writeUTF("Welcome to wikitechy.com");

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

      while(dataInput.available() > 0) {
         String a = dataInput.readUTF();
         System.out.print(a);
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

Welcome to wikitechy.com

Related Searches to Java - DataOutputStream class and its methods