本文為大家分享了FileOutputStream流的write方法,供大家參考,具體內容如下
/*------------------------FileOutputStream:....//輸出流,字節流....//write(byte[] b)方法: 將b.length個字節從指定字節數組寫入此文件輸出流中....//write(byte[] b, int off, int len)方法:將指定字節數組中從偏移量off開始的len個字節寫入此文件輸出流-------------------------*/package pack02;import java.io.*;public class Demo { public static void main(String[] args) { testMethod1(); //從程序中向一個文件寫入數據 testMethod2(); //復制一個文件的內容到另一個文件 } //從程序中向一個文件寫入數據 public static void testMethod1() { File file1 = new File("d:/TEST/MyFile1.txt"); FileOutputStream fos = null; try { fos = new FileOutputStream(file1); //將FileOutputStream流對象連接到file1代表的文件 fos.write( new String("This is MyFile1.txt").getBytes() ); //使用方法write(byte[] b),即向文件寫入一個byte數組的內容 //這里創建一個字符串對象,并調用方法getBytes(),將其轉換成一個字符數組作為write(byte[] b)的形參 //當文件MyFile1.txt不存在時,該方法會自動創建一個這個文件;當文件已經存在時,該方法會創建一個新的同名文件進行覆蓋并寫入數組內容 } catch (IOException e) { e.printStackTrace(); } finally { if( fos != null ) try { fos.close(); //關閉流 } catch (IOException e) { e.printStackTrace(); } } } //從一個文件讀取數據,然后寫入到另一個文件中;相當于內容的復制 public static void testMethod2() { File fileIN = new File("d:/TEST/MyFile2.txt"); //定義輸入文件 File fileOUT = new File("d:/TEST/MyFile3.txt"); //定義輸出文件 FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(fileIN); //輸入流連接到輸入文件 fos = new FileOutputStream(fileOUT); //輸出流連接到輸出文件 byte[] arr = new byte[10]; //該數組用來存入從輸入文件中讀取到的數據 int len; //變量len用來存儲每次讀取數據后的返回值 while( ( len=fis.read(arr) ) != -1 ) { fos.write(arr, 0, len); }//while循環:每次從輸入文件讀取數據后,都寫入到輸出文件中 } catch (IOException e) { e.printStackTrace(); } //關閉流 try { fis.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
注:希望與各位讀者相互交流,共同學習進步。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選