字节流Stream操作单元是字节,按流的方向分为字节输入流InputStream和字节输出流OutputStream。
InputStream
是所有字节输入流的父类,包含两个核心方法:
int read() 从流中一次读取一个字节,返回类型虽然为四个字节的int型,实际上只填充最后一个字节,前三个都为0。
int read(byte[] buffer) 从流中连续读取多个可用字节,最不超过buffer.length中缓冲在buffer数组中,返回实际读取字节数量。
OutputStream
是所有字节输出流的父类,包含两个核心方法:
void write(int n) 将参数最后一个字节输出到流中。
void write(byte[] buffer,int offset,int length) 将缓冲在buffer数组的字节信息从索引offset开始连接取length个输出到流中。
本文以File作为输入和输出目标和源介绍文件字节输入流FileInputStream和FileOutputStream这两个流类来复制d:\a.jpg至e:\a.jpg。。
示例代码:
public static void main(String[] args) { FileInputStream fis=null; FileOutputStream fos=null; try { fis=new FileInputStream("d:\\a.jpg"); fos=new FileOutputStream("e:\\b.jpg"); int n=-1; while((n=fis.read())!=-1){ fos.write(n); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(fos!=null){ fos.flush(); fos.close(); } if(fis!=null)fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } | | |