首页 > 编程语言 > 详细

Java学习之IO流(字节流)

时间:2020-01-02 14:23:55      阅读:85      评论:0      收藏:0      [点我收藏+]

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

字节流的体系:

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     }

 

Java学习之IO流(字节流)

原文:https://www.cnblogs.com/WarBlog/p/12132516.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!