前言

  《Java I/O 从0到1》系列上一章节,介绍了File 类,这一章节介绍的是IO的核心 输入输出。I/O类库常使用流这个抽象概念。代表任何有能力产出数据的数据源对象或者是有能力接受数据的接收端对象。

  流 屏蔽了实际的I/0设备中处理数据的细节。Java类库中的I/O类库分为输入输出两部分。InputStram或Reader 派生而来的类都含有 read() 基本方法,用于 读 取单个字节或者字节数组。同样,任何自OutputStream或Writer 派生而来的类都含有名为write()基本方法,用于 写 单个字节或者字节数组。但是,我们通常不会用到这些方法,他们之所以存在是因为别的类可以使用它们,以便提供更有用的接口。因此,很少使用单一的类来创建流对象,而是通过叠合多个对象来提供所期望的功能。摘自《Java 编程思想第四版》

下面呢,提供一个整理的IO思维导图(查看图片,点击图片右键 选择 新标签页中打开):

《Java I/O 从0到1》 - 第Ⅱ滴血 “流”

 

Xmind下载链接:http://pan.baidu.com/s/1gfrLcf5


 

InputStream:用来表示从不同数据源产生输入的类。数据源包括:字节数组,String对象,文件,“管道”等 。引用《Java 编程思想第四版》中图片。

OutputStream:决定了输出所要去往的目标。

 

字节流

  字节流对应的类是InputStream和OutputStream,而在实际开发过程中,需要根据不同的类型选用相应的子类来处理。

  a. 先根据需求进行判定, 则使用 InputStream 类型;   则使用 OutputStream 类型

  b. 在判定媒介对象什么类型,然后使用对应的实现类。  eg: 媒介对象是 文件  则使用FileInputStream FileOutputStream 进行操作。

 

  方法

  1.    int  read(byte[] b) 从此输入流中读取一个数据字节。

  2.  int read(byte[] b, int off, int len)  从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。

  3.   void   write(byte[] b)  将 b.length 个字节写入此输出流。

  4.    void   write(byte[] b, int off, int len)  将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。

 1 /**
 2      * 
 3      * Title: writeByteToFile
 4      * Description: 字节流写文件
 5      * @author yacong_liu Email:2682505646@qq.com
 6      * @date 2017年9月20日下午5:34:41
 7      */
 8     private static void writeByteToFile() {
 9         String str = new String("Hello Everyone!,My name is IO");
10         byte[] bytes = str.getBytes();
11         File file = new File("D:" + File.separator + "tmp" + File.separator + "hello.txt");
12         OutputStream os = null;
13         try {
14             os = new FileOutputStream(file);
15             os.write(bytes);
16             System.out.println("write success");
17         } catch (FileNotFoundException e) {
18             e.printStackTrace();
19         } catch (IOException e) {
20             e.printStackTrace();
21         } finally {
22             try {
23                 os.close();
24             } catch (IOException e) {
25                 e.printStackTrace();
26             }
27         }
28     }
字节流 写 文件

相关文章:

  • 2022-12-23
  • 2021-11-10
  • 2021-11-28
  • 2021-06-04
  • 2021-05-23
  • 2021-05-01
  • 2021-05-17
猜你喜欢
  • 2022-12-23
  • 2021-06-05
  • 2021-12-05
  • 2022-12-23
  • 2021-12-29
  • 2021-05-14
  • 2021-09-30
相关资源
相似解决方案