A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Kelvinhu 中级黑马   /  2014-4-11 17:40  /  912 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Kelvinhu 于 2014-4-11 17:42 编辑



IO流的概念:通过数据流、序列化和文件系统提供系统输入和输出。
IO流 提供的Api包在java.io包内。

                                            流类图结构
字节流的:
InputStream  



public abstract int read()                  throws IOException
从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值-1。在输入数据可用、检测到流末尾或者抛出异常前,此方法一直阻塞。



public int read(byte[] b)         throws IOException参数:b - 存储读入数据的缓冲区。返回:
读入缓冲区的总字节数;如果因为已经到达流末尾而不再有数据可用,则返回 -1。



public int read(byte[] b,                int off,                int len)         throws IOException参数:b - 读入数据的缓冲区。off - 数组 b 中将写入数据的初始偏移量。len - 要读取的最大字节数。返回:
读入缓冲区的总字节数;如果因为已到达流末尾而不再有数据可用,则返回 -1。


OutputStream:

public abstract void write(int b)                    throws IOException将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。
OutputStream 的子类必须提供此方法的实现。





public void write(byte[] b)           throws IOException参数:b - 数据。




public void write(byte[] b,                  int off,                  int len)           throws IOException

参数:b - 数据。off - 数据中的初始偏移量。len - 要写入的字节数。



public void flush()           throws IOException刷新此输出流并强制写出所有缓冲的输出字节。flush 的常规协定是:如果此输出流的实现已经缓冲了以前写入的任何字节,则调用此方法指示应将这些字节立即写入它们预期的目标。
如果此流的预期目标是由基础操作系统提供的一个抽象(如一个文件),则刷新此流只能保证将以前写入到流的字节传递给操作系统进行写入,但不保证能将这些字节实际写入到物理设备(如磁盘驱动器)。
OutputStream 的 flush 方法不执行任何操作。



  1. import java.io.*;
  2. public class TestInputStream {
  3.         public static void main(String args[]) {
  4.                         testBufferedStream();
  5.         }


  6.         static void testBufferedStream() {
  7.                 BufferedInputStream bis = null;
  8.                 BufferedOutputStream bos = null;
  9.                 try {
  10.                         bis = new BufferedInputStream(new FileInputStream("D:\\java\\Test.java"));
  11.                         bos = new BufferedOutputStream(new FileOutputStream("D:\\java\\Test.txt"));
  12.                 } catch (FileNotFoundException e) {
  13.                         System.out.println("系统找不到该文件");
  14.                         e.printStackTrace();
  15.                 }
  16.                
  17.                 byte bts[] = new byte[1024];
  18.                 try {
  19.                         while ((bis.read(bts))!=-1)
  20.                         {
  21.                                 bos.write(bts);
  22.                         }
  23.                         bos.flush();
  24.                         bis.close();
  25.                         bos.close();
  26.                 } catch (IOException e) {
  27.                         e.printStackTrace();
  28.                 }

  29.         }
  30. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马