流:流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。
字节流:字节流以字节(8bit)为单位,字节流能处理所有类型的数据(如图片、avi等)。
字符流:字符流以字符为单位,根据码表映射字符,一次可能读多个字节,字符流只能处理字符类型的数据。
输入流:输入流只能进行读操作
输出流:输出流只能进行写操作
流的简单小示例
public class TestInputStream { public static void main(String[] args) { FileInputStream fis=null; try { //1、创建流对象 fis = new FileInputStream("e:\\bb.txt"); //3、读取 读取一个字节 /* int i = -1; while ((i=fis.read()) != -1) { System.out.println((char)i); } */ //此处 数组的长度 一般都是1024的倍数 效率最高 byte[] b = new byte[1024]; abc:while(fis.read(b) != -1){ if (fis.available() < b.length) { b = new byte[fis.available()]; fis.read(b); System.out.println(new String(b)); break abc; } System.out.print(new String(b)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { //2、关闭流 if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
public class TestOutputStream { public static void main(String[] args) { FileOutputStream fos = null; try { //1、创建流对象 fos = new FileOutputStream("src/Air.txt",false); String str = "你好!!!"; //3、写出 fos.write(str.getBytes()); //4、输出流 刷新 fos.flush(); System.out.println("输出完毕~~~"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { //2、关闭流 if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } }