Java学习之IO流(字节流)

字节流:顾名思义操作(读、写)文件的流对象

字节流的体系:

1、InputStream
  |--FileInputStream:将文件数据读取到缓冲区中

2、OutputStream
  |--FileOutputStream:将缓冲区数据写入文件

一、FileInputStream和FileOutputStream

 1 // 文件过大,有可能内存溢出
 2     private static void copy_3() throws IOException {
 3     FileInputStream fis = new FileInputStream("源文件路径");
 4     FileOutputStream fos = new FileOutputStream("目标文件路径");
 5     // available()文件大小
 6     byte[] buf = new byte[fis.available()];
 7     fis.read(buf);
 8     fos.write(buf);
 9     fis.close();
10     fos.close();
11     }
12 
13     // 使用缓冲区对象
14     private static void copy_2() throws IOException {
15     FileInputStream fis = new FileInputStream("源文件路径");
16     BufferedInputStream bfis = new BufferedInputStream(fis);
17     FileOutputStream fos = new FileOutputStream("目标文件路径");
18     BufferedOutputStream bfos = new BufferedOutputStream(fos);
19 
20     int ch = 0;
21     while ((ch = bfis.read()) != -1) {
22         bfos.write(ch);
23     }
24     bfis.close();
25     bfos.close();
26     }
27 
28     // 自定义缓冲区
29     private static void copy_1() throws IOException {
30     FileInputStream fis = new FileInputStream("源文件路径");
31     FileOutputStream fos = new FileOutputStream("目标文件路径");
32     byte[] buf = new byte[1024];
33     int len = 0;
34     while ((len = fis.read(buf)) != -1) {
35         fos.write(buf, 0, len);
36     }
37     fis.close();
38     fos.close();
39     }

 

posted @ 2020-01-02 13:43  一杯水M  阅读(230)  评论(0编辑  收藏  举报