本文為大家分享了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(); } } } |
注:希望與各位讀者相互交流,共同學習進步。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/EarthPioneer/p/9360029.html