當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.io.FileOutputStream.write()用法及代碼示例


描述

這個java.io.FileOutputStream.write(byte[] b, int off, int len)方法將從偏移量 off 開始的指定字節數組中的 len 個字節寫入此文件輸出流。

聲明

以下是聲明java.io.FileOutputStream.write(byte[] b, int off, int len)方法 -

public void write(byte[] b, int off, int len)

參數

  • b− 源緩衝區。

  • off− 數據中的起始偏移量。

  • len− 要寫入的字節數。

返回值

此方法不返回任何值。

異常

IOException− 如果發生任何 I/O 錯誤。

示例

下麵的例子展示了 java.io.FileOutputStream.write(byte[] b, int off, int len) 方法的用法。

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      FileOutputStream fos = null;
      FileInputStream fis = null;
      byte[] b = {65,66,67,68,69};
      int i = 0;
      char c;
      
      try {
         // create new file output stream
         fos = new FileOutputStream("C://test.txt");
         
         // writes byte to the output stream
         fos.write(b, 2, 3);
         
         // flushes the content to the underlying stream
         fos.flush();
         
         // create new file input stream
         fis = new FileInputStream("C://test.txt");
         
         // read till the end of the file
         while((i = fis.read())!=-1) {
         
            // convert integer to character
            c = (char)i;
            
            // prints
            System.out.print(c);
         }
         
      } catch(Exception ex) {
         // if an error occurs
         ex.printStackTrace();
      } finally {
         // closes and releases system resources from stream
         if(fos!=null)
            fos.close();
         if(fis!=null)
            fis.close();
      }
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

CDE

相關用法


注:本文由純淨天空篩選整理自 Java.io.FileOutputStream.write() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。