Home » Java programming language

Java RandomAccessFile writeBytes() Method with Example

RandomAccessFile Class writeBytes() method: Here, we are going to learn about the writeBytes() method of RandomAccessFile Class with its syntax and example.
Submitted by Preeti Jain, on March 23, 2020

RandomAccessFile Class writeBytes() method

  • writeBytes() method is available in java.io package.
  • writeBytes() method is used to write the sequence of bytes (i.e. string) to the file. Every character exists in the string is written out in a sequence by skipping its higher 8 bits
  • writeBytes() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • writeBytes() method may throw an exception at the time of writing bytes.
    IOException: This exception may throw an exception while performing input/output operation.

Syntax:

    public final void writeBytes(String str);

Parameter(s):

  • String str – represents the string to write.

Return value:

The return type of this method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void writeBytes(String str) method of
// RandomAccessFile

import java.io.*;
class RAFWriteBytes {
 public static void main(String[] args) throws Exception {
  // Instantiate a random access file
  // object with file name and permissions
  RandomAccessFile ra_f = new RandomAccessFile("e:/includehelp.txt", "rw");

  // By using writeBytes() method is to 
  // write sequence of bytes i.e. string
  // at a time to the file
  ra_f.writeBytes("Welcome, in Java World!!!");

  // by using seek() method is to 
  // set the current file indicator
  // from where read/write could 
  // start i.e. we set here 0 so reading
  // will be done from 0 till EOF
  ra_f.seek(0);

  // By using readLine() method is to 
  // read string from this file
  System.out.println("ra_f.readLine(): " + ra_f.readLine());

  // By using close() method isto
  // close this stream ran_f
  ra_f.close();
 }
}

Output

ra_f.readLine(): Welcome, in Java World!!!!!


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.