Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java - DataOutputStream writeBytes(String s) method



Description

The Java DataOutputStream writeBytes(String s) method 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. If no exception is thrown, the counter written is incremented by the length of s.

Declaration

Following is the declaration for java.io.DataOutputStream.writeBytes(String s) method −

public final void writeBytes(String s)

Parameters

s − Source as string written as bytes to the stream.

Return Value

This method does not return any value.

Exception

IOException − If an I/O error occurs.

Example - Usage of DataOutputStream writeBytes(String s) method

The following example shows the usage of Java DataOutputStream writeBytes(String s) method. We've created ByteArrayOutputStream and DataOutputStream reference. A String is initialized with some text. A ByteArrayOutputStream object is created. Then DataOutputStream is initialized with ByteArrayOutputStream object created before. String is written to stream using writeBytes() method. As next step, stream is flushed using flush() method and ByteArrayOutputStream is iterated to print the bytes written to the stream as characters. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      ByteArrayOutputStream baos = null;
      DataOutputStream dos = null;
      String s = "Hello World!!";      
      try {
         
         // create byte array output stream
         baos = new ByteArrayOutputStream();
         
         // create data output stream
         dos = new DataOutputStream(baos);
         
         // write to the output stream from the string
         dos.writeBytes(s);
         
         // flushes bytes to underlying output stream
         dos.flush();
   
         // for each byte in the baos buffer content
         for(byte b:baos.toByteArray()) {
         
            // print value
            System.out.print(b + " ");
         }         
      } catch(Exception e) {
         
         // if any error occurs
         e.printStackTrace();
      } finally {
         
         // releases all system resources from the streams
         if(baos!=null)
            baos.close();
         if(dos!=null)
            dos.close();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

72 101 108 108 111 32 87 111 114 108 100 33 33

Example - Usage of DataOutputStream writeBytes(String s) method

The following example shows the usage of Java DataOutputStream writeBytes(String s) method. We've created ByteArrayOutputStream and DataOutputStream reference. A ByteArrayOutputStream object is created. Then DataOutputStream is initialized with ByteArrayOutputStream object created before. As a special case, we're closing the stream and then writing the string to the stream to check if it allows writing to a closed stream. As next step, stream is flushed using flush() method and ByteArrayOutputStream is iterated to print the bytes written to the stream as characters. Finally we're closing all the streams.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      ByteArrayOutputStream baos = null;
      DataOutputStream dos = null;           
      try {
         
         // create byte array output stream
         baos = new ByteArrayOutputStream();
         
         // create data output stream
         dos = new DataOutputStream(baos);
         
         // close the stream
         dos.close();
		 
         // write to the output stream from the string
         dos.writeBytes("Hello World!!");
         
         // flushes bytes to underlying output stream
         dos.flush();
   
         // for each byte in the baos buffer content
         for(byte b:baos.toByteArray()) {
            
            // print value
            System.out.print(b + " ");
         }
         
      } catch(Exception e) {
         
         // if any error occurs
         e.printStackTrace();
      } finally {
         
         // releases all system resources from the streams
         if(baos!=null)
            baos.close();
         if(dos!=null)
            dos.close();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

72 101 108 108 111 32 87 111 114 108 100 33 33 

Example - Writing and Reading a String Using writeBytes()

The following example shows the usage of Java DataOutputStream writeBytes(String s) method.

DataOutputStreamDemo.java

package com.tutorialspoint;

import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) {
      try {
         // Create a DataOutputStream to write to a file
         FileOutputStream fileOutput = new FileOutputStream("output.dat");
         DataOutputStream dataOutput = new DataOutputStream(fileOutput);

         // Write a string as bytes
         String message = "Hello, World!";
         dataOutput.writeBytes(message); // Writes each character as a single byte

         // Close the output stream
         dataOutput.close();
         System.out.println("String successfully written to output.dat");

         // Read the bytes back
         FileInputStream fileInput = new FileInputStream("output.dat");
         DataInputStream dataInput = new DataInputStream(fileInput);

         // Read the bytes and convert them back to a string
         byte[] buffer = new byte[message.length()];
         dataInput.readFully(buffer);
         String readMessage = new String(buffer); // Convert byte array to string

         // Print the read string
         System.out.println("String read from file: " + readMessage);

         // Close the input stream
         dataInput.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

String successfully written to output.dat
String read from file: Hello, World!

Explanation

Writing a String as Bytes

  • FileOutputStream creates a file (output.dat).

  • writeBytes(message) writes each character as a single byte, which works fine for ASCII characters.

  • The file will contain: Hello, World!

Reading the String

  • FileInputStream opens the file.

  • readFully(buffer) reads the exact number of bytes.

  • new String(buffer) converts the bytes back into a readable string.

java_io_dataoutputstream.htm
Advertisements