Home » Java programming language

Java FileDescriptor sync() Method with Example

FileDescriptor Class sync() method: Here, we are going to learn about the sync() method of FileDescriptor Class with its syntax and example.
Submitted by Preeti Jain, on April 02, 2020

FileDescriptor Class sync() method

  • sync() method is available in java.io package.
  • sync() method is used to synchronize all the system buffer with the underlying device.
  • sync() 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.
  • sync() method may throw an exception at the time of synchronizing.
    SyncFailedException: This exception may throw when the buffer cannot be flushed or the system cannot be sure synchronization of all the buffers with the underlying device.

Syntax:

    public void sync();

Parameter(s):

  • It does not accept any parameter.

Return value:

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

Example:

// Java program to demonstrate the example 
// of void sync() method of FileDescriptor

import java.io.*;

public class SyncOfFD {
 public static void main(String[] args) throws Exception {
  FileOutputStream os_stm = null;

  try {
   // Instantiates FileOutputStream 
   os_stm = new FileOutputStream("D:\\includehelp.txt");

   // By using getFD() method is to get
   // the file descriptor
   FileDescriptor file_des = os_stm.getFD();

   // By using write() method is to
   // write corresponding char 'A' to
   // the output stream os_stm 
   os_stm.write(65);

   // By using sync() method is to
   // sync the data to the file
   file_des.sync();
   System.out.println("Sync() executed ");
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {
   // with the help of this block is to
   // free all necessary resources linked
   // with the stream
   if (os_stm != null) {
    os_stm.close();
   }
  }
 }
}

Output

Sync() executed


Comments and Discussions!

Load comments ↻





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