Java - FileDescriptor sync() method



Description

The Java FileDescriptor sync() method forces all system buffers to be written to the disk. It ensures that data written to a file is physically stored on the disk, preventing data loss in case of a system crash.

Declaration

Following is the declaration for java.io.FileDescriptor.sync() method −

public void sync()

Parameters

NA

Return Value

The method does not return any value.

Exception

SyncFailedException− This exception is thrown when the buffer cannot be flushed or because the system cannot guarantee synchronization of all the buffers with the physical media.

Example - Usage of FileDescriptor sync() method

The following example shows the usage of Java FileDescriptor sync() method.

FileDescriptorDemo.java

package com.tutorialspoint;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileDescriptorDemo {
   public static void main(String[] args) {      
      FileInputStream fis = null;
      FileOutputStream fos = null;
      FileDescriptor fd = null;
      byte[] b = {65,66,67,68,69,70};
      
      try {
         fos = new FileOutputStream("test.txt");
         fd = fos.getFD();
         
         // writes byte to file output stream
         fos.write(b);
         
         // flush data from the stream into the buffer
         fos.flush();
         
         // confirms data to be written to the disk
         fd.sync();
         
         // create input stream
         fis = new FileInputStream("test.txt");
         
         int value = 0;
         
         // for every available bytes
         while((value = fis.read())!= -1) {
         
            // converts bytes to char
            char c = (char)value;
            
            // prints char
            System.out.print(c);
         }
         
         // print
         System.out.print("\nSync() successfully executed!!");
         
         fos.close();
         fis.close();
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      } 
   }
}

Output

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

ABCDEF
Sync() successfully executed!!

Example - Using sync() to Ensure Data is Written to Disk

The following example shows the usage of Java FileDescriptor sync() method.

FileDescriptorDemo.java

package com.tutorialspoint;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileDescriptorDemo {
   public static void main(String[] args) {
      File file = new File("sync_example.txt");

      try (FileOutputStream fos = new FileOutputStream(file)) {
         FileDescriptor fd = fos.getFD(); // Get file descriptor

         // Write data to the file
         fos.write("Hello, this is a test for sync method.".getBytes());

         // Force data to be written to disk
         fd.sync();

         System.out.println("Data successfully written and synced to disk.");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

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

Data successfully written and synced to disk.

Explanation

  • A FileOutputStream is created for "sync_example.txt".

  • The getFD() method retrieves the file descriptor (FileDescriptor object).

  • Data is written to the file using fos.write().

  • The sync() method is called on the file descriptor, ensuring that the data is immediately written to disk.

  • The file is automatically closed using try-with-resources.

Example - Using sync() in a Buffered Stream

The following example shows the usage of Java FileDescriptor sync() method.

FileDescriptorDemo.java

package com.tutorialspoint;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileDescriptorDemo {
    public static void main(String[] args) {
        File file = new File("buffered_sync_example.txt");

        try (FileOutputStream fos = new FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {

            FileDescriptor fd = fos.getFD(); // Get file descriptor

            // Write data in a buffered stream
            bos.write("Buffered stream sync example.".getBytes());

            // Flush the buffer
            bos.flush();

            // Force data to be written to disk
            fd.sync();

            System.out.println("Buffered data successfully written and synced to disk.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

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

Buffered data successfully written and synced to disk.

Explanation

  • A BufferedOutputStream wraps the FileOutputStream for efficient writing.

  • Data is written to the buffered stream.

  • bos.flush() is called to ensure buffered data is passed to the underlying file stream.

  • The sync() method is called on the file descriptor, ensuring the data is physically written to disk.

  • The file is closed automatically using try-with-resources.

java_io_filedescriptor.htm
Advertisements