Java分享筆記:FileOutputStream流的write方法


 1 /*------------------------
 2 FileOutputStream:
 3 ....//輸出流,字節流
 4 ....//write(byte[] b)方法: 將b.length個字節從指定字節數組寫入此文件輸出流中
 5 ....//write(byte[] b, int off, int len)方法:將指定字節數組中從偏移量off開始的len個字節寫入此文件輸出流
 6 -------------------------*/
 7 package pack02;
 8 
 9 import java.io.*;
10 
11 public class Demo {
12     
13     public static void main(String[] args) {
14         
15         testMethod1(); //從程序中向一個文件寫入數據
16         testMethod2(); //復制一個文件的內容到另一個文件
17     }
18     
19     //從程序中向一個文件寫入數據
20     public static void testMethod1() {
21         
22         File file1 = new File("d:/TEST/MyFile1.txt");
23         FileOutputStream fos = null;
24         
25         try {
26             
27             fos = new FileOutputStream(file1); //將FileOutputStream流對象連接到file1代表的文件
28             
29             fos.write( new String("This is MyFile1.txt").getBytes() );
30             //使用方法write(byte[] b),即向文件寫入一個byte數組的內容
31             //這里創建一個字符串對象,並調用方法getBytes(),將其轉換成一個字符數組作為write(byte[] b)的形參
32             //當文件MyFile1.txt不存在時,該方法會自動創建一個這個文件;當文件已經存在時,該方法會創建一個新的同名文件進行覆蓋並寫入數組內容
33             
34         } catch (IOException e) {
35             
36             e.printStackTrace();
37             
38         } finally {
39             
40             if( fos != null )
41                 try {
42                     fos.close(); //關閉流
43                 } catch (IOException e) {
44                     e.printStackTrace();
45                 }
46         }
47     }
48     
49     //從一個文件讀取數據,然后寫入到另一個文件中;相當於內容的復制
50     public static void testMethod2() {
51         
52         File fileIN = new File("d:/TEST/MyFile2.txt"); //定義輸入文件
53         File fileOUT = new File("d:/TEST/MyFile3.txt"); //定義輸出文件
54         
55         FileInputStream fis = null;
56         FileOutputStream fos = null;
57         
58         try {
59             
60             fis = new FileInputStream(fileIN); //輸入流連接到輸入文件
61             fos = new FileOutputStream(fileOUT); //輸出流連接到輸出文件
62             
63             byte[] arr = new byte[10]; //該數組用來存入從輸入文件中讀取到的數據
64             int len; //變量len用來存儲每次讀取數據后的返回值
65             
66             while( ( len=fis.read(arr) ) != -1 ) {
67                 fos.write(arr, 0, len);
68             }//while循環:每次從輸入文件讀取數據后,都寫入到輸出文件中
69             
70         } catch (IOException e) {
71             e.printStackTrace();
72         }
73         
74         //關閉流
75         try {
76             fis.close();
77             fos.close();
78         } catch (IOException e) {
79             e.printStackTrace();
80         }
81     }
82     
83 }

注:希望與各位讀者相互交流,共同學習進步。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM