字节流类为处理字节式输入/输出提供了丰富的环境。

一个字节流可以和其他任何类型的对象并用,包括二进制数据。

这样的多功能性使得字节流对很多类型的程序都很重要。

字节流类以InputStream  和OutputStream为顶层。


一、InputStream(输入流)

InputStream 是一个定义了Java 流式字节输入模式的抽象类

该类的所有方法在出错条件下引发一个IOException  异常

 
  
  1. //返回当前可读的输入字节数  
  2. int available( )    
  3. //关闭输入源。关闭之后的读取会产生IOException异常  
  4. void close( )   
  5. //如果下一个字节可读则返回一个整型,遇到文件尾时返回-1  
  6. int read()   
  7. //试图读取buffer.length个字节到buffer中,并返回实际成功读取的字节数。遇到文件尾时返回-1   
  8. int read(byte buffer[ ])   
  9. //重新设置输入指针到先前设置的标志处   
  10. void reset( )  
  11. //在输入流的当前点放置一个标记。该流在读取numBytes个字节前都保持有效   
  12. void mark(int numBytes)  
  13. //如果调用的流支持mark( )/reset( )就返回true   
  14. boolean markSupported( )  
  15. //忽略numBytes个输入字节,返回实际忽略的字节数  
  16. ong skip(long numBytes)  

二、OutputStream(输出流)

OutputStream是定义了流式字节输出模式的抽象类。

该类的所有方法返回一个void 值 并且在出错情况下引发一个IOException异常。

 
  
  1. //关闭输出流。关闭后的写操作会产生IOException异常  
  2. void close( )  
  3. //定制输出状态以使每个缓冲器都被清除,也就是刷新输出缓冲区 
  4. void flush( )  
  5. //向输出流写入单个字节。注意参数是一个整型数,它允许你不必把参数转换成字节型就可以调用write()  
  6. void write(int b) 
  7. //向一个输出流写一个完整的字节数组 
  8. void write(byte buffer[ ])  
  9. //写数组buffer以buffer[offset]为起点的numBytes个字节区域内的内容 
  10. void write(byte buffer[ ], int offset, int numBytes) 

三、FileInputStream(文件输入流)

FileInputStream  类创建一个能从文件读取字节的InputStream  类,它们都能引发FileNotFoundException 异常

 
  
  1. FileInputStream(String filepath)  
  2. FileInputStream(File fileObj) 

 

filepath  是文件的全称路径,fileObj是描述该文件的File对象。

 

下面的例子创建了两个使用同样磁盘文件且各含一个上述构造函数的FileInputStreams类:

 
  
  1. public static void main(String[] args) { 
  2.     try { 
  3.         FileInputStream stream=new FileInputStream("D:/test/txt"); 
  4.         FileInputStream stream2=new FileInputStream(new File("D:/test/txt")); 
  5.     } catch (FileNotFoundException e) { 
  6.         // TODO Auto-generated catch block 
  7.         e.printStackTrace(); 
  8.     } 

 

 ↑↑↑尽管第一个构造函数可能更常用到,第二个构造函数允许在把文件赋给输入流之前用File 方法更进一步检查文件。

 当一个FileInputStream 被创建时,它可以被公开读取。FileInputStream重载了抽象类InputStream 的六个方法,mark( ) 和reset( ) 方法不被重载,任何关于使用FileInputStream的reset() 尝试都会生成IOException异常。

↓↓↓下面的例题说明了怎样读取单个字节、字节数组以及字节数组的子界。它同样阐述了怎样运用available( ) 判定剩余的字节个数及怎样用skip( ) 方法跳过不必要的字节。该程序读取它自己的源文件:

 
  
  1. public static void main(String[] args) { 
  2.     int size; 
  3.     try { 
  4.         InputStream f = new FileInputStream("D:/test.txt"); 
  5.  
  6.         System.out.println("\n当前可读的输入字节数:" + (size = f.available())); 
  7.  
  8.         // 读取单个字节 
  9.         System.out.print("读取前文件中的前两个字节:"); 
  10.         for (int i = 0; i < 2; i++) { 
  11.             System.out.print((char) f.read()); 
  12.         } 
  13.         System.out.println(); 
  14.  
  15.         System.out.println("\n当前可读的输入字节数:" + (size = f.available())); 
  16.  
  17.         // 读取字节数组 
  18.         byte b[] = new byte[10]; 
  19.         if (f.read(b) != 10) { 
  20.             System.out.println("不能读取10字节"); 
  21.         } 
  22.         ; 
  23.         System.out.println(new String(b, 010)); 
  24.         System.out.println("\n当前可读的输入字节数:" + (size = f.available())); 
  25.  
  26.         // 使用用skip()方法 
  27.         System.out.println("执行skip(2)跳跃两个字节"); 
  28.         f.skip(2); 
  29.  
  30.         System.out.println("\n当前可读的输入字节数:" + (size = f.available())); 
  31.  
  32.         if (f.read(b, 05) != 5) { 
  33.             System.err.println("不能读取5字节"); 
  34.         } 
  35.         System.out.println(new String(b, 05)); 
  36.         System.out.println("\n当前可读的输入字节数:" + (size = f.available())); 
  37.         f.close(); 
  38.     } catch (FileNotFoundException e) { 
  39.         // TODO Auto-generated catch block 
  40.         e.printStackTrace(); 
  41.     } catch (IOException e) { 
  42.         // TODO Auto-generated catch block 
  43.         e.printStackTrace(); 
  44.     } 
  45.  
  46. // 输出结果 
  47. // ↓↓↓ 
  48.  
  49. // 当前可读的输入字节数:490 
  50. // 读取前文件中的前两个字节:In 
  51. // 
  52. // 当前可读的输入字节数:488 
  53. // the Orien 
  54. // 
  55. // 当前可读的输入字节数:478 
  56. // 执行skip(2)跳跃两个字节 
  57. // 
  58. // 当前可读的输入字节数:476 
  59. // young 
  60. // 
  61. // 当前可读的输入字节数:471 

四、FileOutputStream(文件输出流)

FileOutputStream  创建了一个可以向文件写入字节的类OutputStream,它们可以引发IOException或SecurityException异常

 
  
  1. FileOutputStream(String filePath)  
  2. FileOutputStream(File fileObj)  
  3. FileOutputStream(String filePath, boolean append) 

 filePath是文件的全称路径,fileObj 是描述该文件的File 对象。如果append 为true ,文件以设置搜索路径模式打开。

 

FileOutputStream的创建不依赖于文件是否存在。在创建对象时FileOutputStream在打开输出文件之前创建它。这种情况下你试图打开一个只读文件,会引发一个IOException异常。

 
  
  1. public static void main(String[] args) { 
  2.     try { 
  3.         String source = "Now is the time for all good men\n" 
  4.                 + " to come to the aid of their country\n" 
  5.                 + " and pay their due taxes."
  6.         byte buf[] = source.getBytes(); 
  7.         OutputStream f0; 
  8.  
  9.         f0 = new FileOutputStream("D:/file1.txt"); 
  10.  
  11.         for (int i = 0; i < buf.length; i += 2) { 
  12.             f0.write(buf[i]); 
  13.         } 
  14.         f0.close(); 
  15.  
  16.         OutputStream f1 = new FileOutputStream("D:/file2.txt"); 
  17.         f1.write(buf); 
  18.         f1.close(); 
  19.  
  20.         OutputStream f2 = new FileOutputStream("D:/file3.txt"); 
  21.         f2.write(buf, buf.length - buf.length / 4, buf.length / 4); 
  22.         f2.close(); 
  23.     } catch (FileNotFoundException e) { 
  24.         // TODO Auto-generated catch block 
  25.         e.printStackTrace(); 
  26.     } catch (IOException e) { 
  27.         // TODO Auto-generated catch block 
  28.         e.printStackTrace(); 
  29.     } 
  30.  
  31. // 输出结果 
  32. // ↓↓↓ 
  33.  
  34. // file1.txt内容: 
  35. // Nwi h iefralgo e 
  36. // t oet h i ftercuty n a hi u ae. 
  37.  
  38.  
  39. // file2.txt内容: 
  40. // Now is the time for all good men 
  41. // to come to the aid of their country 
  42. // and pay their due taxes. 
  43.  
  44.  
  45. // file3.txt内容: 
  46. // nd pay their due taxes. 

五、ByteArrayInputStream(字节数组输入流) 

ByteArrayInputStream是把字节数组当成源的输入流。

 
  
  1. ByteArrayInputStream(byte array[])   
  2. ByteArrayInputStream(byte array[], int start, int numBytes)   

 

↑↑↑array是输入源。第二个构造函数创建了一个InputStream 类,该类从字节数组的子集生成,以start 指定索引的字符为起点,长度由numBytes决定。

 
  
  1. public static void main(String[] args) { 
  2.         String string = "abcdefghijklmnopqrstuvwxyz"
  3.         byte b[] = string.getBytes(); 
  4.  
  5.         // 包含整个字母表中小写字母 
  6.         ByteArrayInputStream stream = new ByteArrayInputStream(b); 
  7.         // 包含开始的十个字母。 
  8.         ByteArrayInputStream stream2 = new ByteArrayInputStream(b, 010); 
  9.  
  10.     } 

 

ByteArrayInputStream实现mark( ) 和reset( ) 方法。然而,如果 mark( )不被调用,reset( )在流的开始设置流指针——该指针是传递给构造函数的字节数组的首地址。

 

下面的例子说明了怎样用reset( ) 方法两次读取同样的输入:

 
  
  1. public static void main(String[] args) { 
  2.     String string = "abcdefg"
  3.     byte b[] = string.getBytes(); 
  4.  
  5.     ByteArrayInputStream stream = new ByteArrayInputStream(b); 
  6.  
  7.     for (int i = 0; i < 2; i++) { 
  8.         int c; 
  9.         while ((c = stream.read()) != -1) { 
  10.             System.out.print(i == 0 ? ((char) c) : Character 
  11.                     .toUpperCase((char) c)); 
  12.  
  13.         } 
  14.         stream.reset(); 
  15.         System.out.println(); 
  16.     } 
  17.  
  18. // 输出结果 
  19. // ↓↓↓ 
  20.  
  21. // abcdefg 
  22. // ABCDEFG 

 

该例先从流中读取每个字符,然后以小写字母形式打印。然后重新设置流并从头读起,这次在打印之前先将字母转换成大写字母。


 

 六、 ByteArrayOutputStream(字节数组输出流)

ByteArrayOutputStream 是一个把字节数组当作输出流的实现

 
  
  1. ByteArrayOutputStream( )  
  2. ByteArrayOutputStream(int numBytes) 

↑↑↑一个32 位字节的缓冲器被生成。第二个构造函数生成一个跟指定numBytes相同位数的缓冲器

 缓冲器保存在ByteArrayOutputStream 的受保护的buf  成员里。缓冲器的大小在需要的情况下会自动增加。缓冲器保存的字节数是由ByteArrayOutputStream 的受保护的count域保存的。
 
  
  1. public static void main(String[] args) { 
  2.     try { 
  3.         ByteArrayOutputStream f = new ByteArrayOutputStream(); 
  4.  
  5.         String s = "abcdefghijklmnopqrstuvwxyz"
  6.         byte buf[] = s.getBytes(); 
  7.  
  8.         f.write(buf); 
  9.  
  10.         System.out.println(f.toString()); 
  11.         for (int i = 0; i < buf.length; i++) { 
  12.             System.out.print((char) buf[i]); 
  13.         } 
  14.         System.out.println(); 
  15.  
  16.         byte b2[] = f.toByteArray(); 
  17.  
  18.         // 写入文件 
  19.         OutputStream f2 = new FileOutputStream("D:/test.txt"); 
  20.         // writeTo( ) 这一便捷的方法将f 的内容写入test.txt 
  21.         f.writeTo(f2); 
  22.         f2.close(); 
  23.  
  24.         f.reset(); 
  25.         for (int i = 0; i < 3; i++) { 
  26.             f.write('X'); 
  27.         } 
  28.  
  29.         System.out.println(f.toString()); 
  30.     } catch (IOException e) { 
  31.         // TODO Auto-generated catch block 
  32.         e.printStackTrace(); 
  33.     } 
  34.  
  35. // 输出结果 
  36. // ↓↓↓ 
  37.  
  38. // abcdefghijklmnopqrstuvwxyz 
  39. // abcdefghijklmnopqrstuvwxyz 
  40. // XXX 

七、过滤字节流

 

过滤流(filtered stream )仅仅是底层透明地提供扩展功能的输入流(输出流)的包装。这些流一般由普通类的方法(即过滤流的一个超类)访问。典型的扩展是缓冲,字符转换和原始数据转换。这些过滤字节流是FilterInputStream  和FilterOutputStream 。

 
  
  1. FilterOutputStream(OutputStream os)   
  2. FilterInputStream(InputStream is)  

八、缓冲字节流

 

对于字节流,缓冲流(buffered stream),通过把内存缓冲器连到输入/输出流扩展一个过滤流类。该缓冲器允许Java 对多个字节同时进行输入/输出操作,提高了程序性能。因为缓冲器可用,所以可以跳过、标记和重新设置流

BufferedInputStream(缓冲输入流)

缓冲输入/输出是一个非常普通的性能优化。Java 的BufferedInputStream  类允许把任何InputStream  类“包装”成缓冲流并使它的性能提高。

 
  
  1. BufferedInputStream(InputStream inputStream)  
  2. BufferedInputStream(InputStream inputStream, int bufSize)  

↑↑↑第一种形式生成了一个默认缓冲长度的缓冲流。第二种形式缓冲器大小是由bufSize传入的。

 

  • 使用内存页或磁盘块等的若干倍的缓冲区大小可以给执行性能带来很大的正面影响。但这是依赖于执行情况的
  • 最理想的缓冲长度一般与主机操作系统、可用内存空间及机器配置有关。合理利用缓冲不需要特别复杂的操作。
  • 一般缓冲大小为8192个字节,给输入/输出流设定一个更小的缓冲器通常是好的方法。
  • 用这样的方法,低级系统可以从磁盘或网络读取数据块并在缓冲器中存储结果。
  • 因此,即使你在InputStream 外同时读取字节数据时,也可以在超过99.9% 的时间里获得快速存储操作。 

 在缓冲器中使用 mark(  )是受限的。意思是说你只能给mark( )定义一个小于流缓冲大小的参数。

该例运用mark(32),该方法保存接下来所读取的32个字节

 
  
  1. public static void main(String[] args) { 
  2.     try { 
  3.         String s = "This is a &copy; copyright symbol " 
  4.                 + "but this is &copy not.\n"
  5.  
  6.         byte buf[] = s.getBytes(); 
  7.         ByteArrayInputStream in = new ByteArrayInputStream(buf); 
  8.         // 包装成缓冲输入流 
  9.         BufferedInputStream f = new BufferedInputStream(in); 
  10.  
  11.         int c; 
  12.         boolean marked = false
  13.  
  14.         while ((c = f.read()) != -1) { 
  15.             switch (c) { 
  16.             case '&'
  17.                 if (marked) { 
  18.                     marked = false
  19.                     f.mark(32); 
  20.                 } else { 
  21.                     marked = true
  22.                 } 
  23.                 break
  24.             case ';'
  25.                 if (marked) { 
  26.                     marked = false
  27.                     System.out.print("(c)"); 
  28.                 } else { 
  29.                     System.out.print((char) c); 
  30.                 } 
  31.                 break
  32.             case ' '
  33.                 if (marked) { 
  34.                     marked = false
  35.                     f.reset(); 
  36.                     System.out.print("&"); 
  37.                 } else { 
  38.                     System.out.print((char) c); 
  39.                 } 
  40.                 break
  41.             default
  42.                 System.out.print((char) c); 
  43.                 break
  44.             } 
  45.         } 
  46.  
  47.     } catch (Exception e) { 
  48.         // TODO: handle exception 
  49.     } 
  50.  
  51. // 输出结果 
  52. // ↓↓↓ 
  53.  
  54. // This is a copy(c) copyright symbol but this is copy 

BufferedOutputStream (缓冲输出流) 

BufferedOutputStream与任何一个OutputStream相同,除了用一个另外的flush( )  方法来保证数据缓冲器被写入到实际的输出设备。因为BufferedOutputStream是通过减小系统写数据的时间而提高性能的,可以调用flush( ) 方法生成缓冲器中待写的数据。 不像缓冲输入,缓冲输出不提供额外的功能,Java 中输出缓冲器是为了提高性能的。

 
  
  1. //第一种形式创建了一个使用512字节缓冲器的缓冲流。 
  2. //第二种形式,缓冲器的大小由bufSize参数传入 
  3. BufferedOutputStream(OutputStream outputStream)  
  4. BufferedOutputStream(OutputStream outputStream, int bufSize)  

PushbackInputStream (推回输入流) 

缓冲的一个新颖的用法是实现推回(pushback ),Pushback 用于输入流允许字节被读取然后返回(即“推回”)到流

 
  
  1. //创建了一个允许一个字节推回到输入流的流对象 
  2. PushbackInputStream(InputStream inputStream)  
  3. //创建了一个具有numBytes长度缓冲区的推回缓冲流 
  4. PushbackInputStream(InputStream inputStream, int numBytes)  

除了具有与InputStream 相同的方法,PushbackInputStream 提供了unread( ) 方法 

 
  
  1. //推回ch的低位字节,它将是随后调用read( ) 方法所返回的下一个字节 
  2. void unread(int ch)  
  3. //返回buffer缓冲器中的字节 
  4. void unread(byte buffer[ ])  
  5. //推回buffer中从offset处开始的numChars个字节 
  6. void unread(byte buffer, int offset, int numChars)  

例子:

 
  
  1. public static void main(String[] args) { 
  2.     try { 
  3.         String s = "if (a == 4) a = 0;\n"
  4.         System.out.println(s); 
  5.         byte buf[] = s.getBytes(); 
  6.         ByteArrayInputStream in = new ByteArrayInputStream(buf); 
  7.         PushbackInputStream push = new PushbackInputStream(in); 
  8.  
  9.         int c; 
  10.  
  11.         while ((c = push.read()) != -1) { 
  12.             switch (c) { 
  13.             case '='
  14.                 if ((c = push.read()) == '=') { 
  15.                     System.out.print(".eq."); 
  16.                 } else { 
  17.                     System.out.print("<-"); 
  18.                     push.unread(c); 
  19.                 } 
  20.                 break
  21.             default
  22.                 System.out.print((char) c); 
  23.                 break
  24.             } 
  25.         } 
  26.     } catch (Exception e) { 
  27.         // TODO: handle exception 
  28.     } 
  29.  
  30. // 输出结果 
  31. // ↓↓↓ 
  32.  
  33. // if (a == 4) a = 0; 
  34. // 
  35. // if (a .eq. 4) a <- 0; 
 PushbackInputStream具有使InputStream生成的 mark(  )  或 reset( )方法失效的副作用。用markSupported(  )来检查你运用mark( )/reset(  )的任何流类。 

 


九、 SequenceInputStream (顺序输入流)

SequenceInputStream 类允许连接多个InputStream 流

 
  
  1. SequenceInputStream(InputStream first, InputStream second)  
  2. SequenceInputStream(Enumeration streamEnum)  

 


 十、PrintStream (打印流)

 

PrintStream 具有本书开始以来我们在System 文件句柄使用过的System.out所有的格式化性能。

 

 
  
  1. PrintStream(OutputStream outputStream)  
  2. PrintStream(OutputStream outputStream, boolean flushOnNewline)  

 

↑↑↑当flushOnNewline 控制Java 每次刷新输出流时,输出一个换行符(\n )。如果flushOnNewline 为true ,自动刷新。若为false ,刷新不能自动进行。第一个构造函数不支持自动刷新。


十一、RandomAccessFile (随机访问文件类)

 

RandomAccessFile 包装了一个随机访问的文件。它不是派生于InputStream 和OutputStream,而是实现定义了基本输入/输出方法的DataInput 和DataOutput接口。它同样支持定位请求——也就是说,可以在文件内部放置文件指针。

 
  
  1. RandomAccessFile(File fileObj, String access)  throws FileNotFoundException  
  2. RandomAccessFile(String filename, String access)  throws FileNotFoundException  

↑↑↑第一种形式,fileObj 指定了作为File  对象打开的文件的名称。第二种形式,文件名是由filename 参数传入的

 

两种情况下,access  都决定允许访问何种文件类型。如果是“r”,那么文件可读不可写,如果是“rw”,文件以读写模式打开。

 
  

//用来设置文件内部文件指针的当前位置,newPos  指文件指针从文件开始以字节方式指定新位置。调用seek( ) 方法后,接下来的读或写操作将在文件的新位置发生。 

  1. void seek(long newPos) throws IOException  

 

 

 

 

 
  
  1. //该方法通过指定的len设置正在调用的文件的长度,该方法可以增长或缩短一个文件。如果文件被加长,增加的部分是未定义的 
  2. void setLength(long len) throws IOException