目录

void sync()

描述 (Description)

java.io.File.sync()方法强制所有系统缓冲区与底层设备同步。

声明 (Declaration)

以下是java.io.File.sync()方法的声明 -

public void sync()

参数 (Parameters)

NA

返回值 (Return Value)

该方法不返回任何值。

异常 (Exception)

SyncFailedException - 当无法刷新缓冲区或系统无法保证所有缓冲区与物理介质同步时,抛出此异常。

例子 (Example)

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

package com.iowiki;
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!!
↑回到顶部↑
WIKI教程 @2018