Java.io.File.sync() 方法



描述

java.io.File.sync() 方法強制所有系統緩衝區與底層裝置同步。

宣告

以下是 java.io.File.sync() 方法的宣告:-

public void sync()

引數

返回值

該方法不返回值。

異常

SyncFailedException - 當緩衝區無法重新整理或系統無法保證所有緩衝區與物理介質同步時,將丟擲此異常。

示例

以下示例顯示了 java.io.File.sync() 方法的使用。

package com.tutorialspoint;

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

public class FileDemo {
   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("c:/java 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("c:/java 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!!");
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      } finally {
         // releases system resources
         if(fos!=null)
            fos.close();
         if(fis!=null)
            fis.close();
      }
   }
}

讓我們編譯並執行以上程式,這將產生以下結果:-

ABCDEF
Sync() successfully executed!!
java_io_filedescriptor.htm
廣告