Java中FileOutputStream流的write方法


本文為大家分享了FileOutputStream流的write方法,供大家參考,具體內容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*------------------------
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();
   }
  }
  
}

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。


免責聲明!

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



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