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 }

注:希望与各位读者相互交流,共同学习进步。

猜你喜欢

转载自www.cnblogs.com/EarthPioneer/p/9360029.html