Java - ObjectOutputStream writeBytes(String str) method



Description

The Java ObjectOutputStream writeBytes(String str) method writes strings of bytes.

  • Writes the low-order byte of each character in the string to the stream (i.e., discards high-order byte).

  • Inherited from DataOutput, which ObjectOutputStream implements.

  • Each character is treated as a single byte, so it's not Unicode-safe - suitable for ASCII only.

  • This is not object serialization − it's raw byte writing.

Declaration

Following is the declaration for java.io.ObjectOutputStream.writeBytes(String str) method.

public void writeBytes(String str)

Parameters

  • val − The string of bytes to be written.

Return Value

This method does not return a value.

Exception

  • IOException − If I/O errors occur while writing to the underlying stream.

Example - Usage of ObjectOutputStream writeBytes(String str) method

The following example shows the usage of ObjectOutputStream writeBytes(String str) method.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String s = "Hello";
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeBytes(s);
         oout.writeBytes("World");

         // close the stream
         oout.close();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print what we wrote before
         for (int i = 0; i < 10; i++) {
            System.out.print("" + (char) ois.readByte());
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Output

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

HelloWorld

Example - Write a basic ASCII string to a file and read it back

The following example shows the usage of ObjectOutputStream writeBytes(String str) method. We're writing "Hello" using writeBytes() and print the result.

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String filename = "ascii_output.txt";

      // Write the string as raw bytes
      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         oos.writeBytes("Hello");
         System.out.println("String written using writeBytes(): Hello");
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Read and print the file
      try (FileInputStream fis = new FileInputStream(filename)) {
         byte[] data = fis.readAllBytes();
         String result = new String(data); // assumes default charset
         System.out.println("Read from file: " + result);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

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

String written using writeBytes(): Hello
Read from file: Hello

Example - Write a formatted ASCII message using writeBytes()

The following example shows the usage of ObjectOutputStream writeBytes(String str) method. We're writing a simple ASCII log entry using writeBytes().

ObjectOutputStreamDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamDemo {
   public static void main(String[] args) {
      String filename = "log_output.txt";

      // Simulate a log entry
      String timestamp = "2024-03-25";
      String level = "INFO";
      String message = "Application started successfully";

      String logEntry = "[" + timestamp + "] [" + level + "] " + message + "\n";

      try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
         oos.writeBytes(logEntry);
         System.out.println("Log entry written using writeBytes():");
         System.out.println(logEntry);
      } catch (IOException e) {
         e.printStackTrace();
      }

      // Read and print the file content
      try (FileInputStream fis = new FileInputStream(filename)) {
         fis.skip(6);
         byte[] data = fis.readAllBytes();
         String result = new String(data);
         System.out.println("Read from file:");
         System.out.println(result);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

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

Log entry written using writeBytes():
[2024-03-25] [INFO] Application started successfully

Read from file:
[2024-03-25] [INFO] Application started successfully

Explanation

  • skip(6) is used because ObjectOutputStream adds some headers before the actual content. The first 6 bytes are headers, in our case.

  • We write a plain ASCII log line using writeBytes().

  • Because it's ASCII-only, there's no data loss.

  • This shows writeBytes() is totally fine for writing logs, IDs, and simple messages - as long as they don't include accented or non-Latin characters.

java_io_objectoutputstream.htm
Advertisements